0

我在一个自由文本文件中有一种情况,在我选择的任何两个字符串匹配之间 - 例如

<hello> and </hello> 

我想用不同的字符串替换第三个字符串匹配的出现,例如 '=' 和 '&EQ;'

例如

hi=I want this equals sign to stay the same,but=<hello>
<I want="this one in the hello tag to be replaced"/>
</hello>,and=of course this one outside the tag to stay the same

变成

hi=I want this equals sign to stay the same,but=<hello>
<I want&EQ;"this one in the hello tag to be replaced"/>
</hello>,and=of course this one outside the tag to stay the same

基本上这是因为一个 XML 正文是在一个值对中发送的,它把事情搞砸了(我是由一个场所发送的这种格式,并且无法控制它

我的直接方法是从 BufferedReader 开始,然后使用 String.indexOf( ) 逐行解析为 StringBuilder 来打开和关闭我们是否在标签中,但是在使用这种方法 20 分钟后,我想到了这一点可能有点蛮力,并且可能有针对此类问题的现有解决方案

我知道这种方法最终会奏效,但我的问题是,是否有更好的方法(即更高级别并使用现有 Java 库/通用框架,例如 Apache Commons 等),这将使其不易出错且更易于维护.即有没有比我采用的方法更智能的方法来解决这个问题?这实际上是蛮力解析。

4

2 回答 2

0

我伟大的难以理解的解决方案如下,它似乎有效。

我很抱歉它很难理解,但它基本上归结为分解和重新分解,多次组合相似的代码。

它将在 'openToken' 和 'closeToken' 的标记之间用字符串 'with' 替换所有出现的字符串 'replace' 并且应该以 mode=false 开头

与生活中的大多数事情一样,RegEx 可能有一种非常聪明简洁的方法来做到这一点

boolean mode=false
StringBuilder output

while( String line = newLine ) {
    mode = bodge( "<hello>", "</hello>", "=", "&EQ;", output, mode );
}



private static boolean bodge( String openToken, String closeToken, String replace, String with, String line, StringBuilder out, boolean mode  ) {

    String comparator = mode ? closeToken : openToken;

    int index = line.indexOf( comparator );

    // drop through straight if nothing interesting
    if( index == -1 ) {
        String outLine = mode ?
                             replacer( line , replace, with ) :
                             line;
        out.append( outLine );
        out.append( "\r\n" );
        return mode;
    }
    else {
        int endOfToken = index + comparator.length();
        String outLine = line.substring(0, endOfToken);
        outLine = mode ?
                      replacer( outLine , replace, with ) :
                      outLine;

        out.append(outLine );
        return bodge( openToken, closeToken, replace, with, line.substring( endOfToken ), out, !mode );
    }
}
于 2013-09-18T17:02:08.140 回答
0

如果您想转义 XML,请查看 Apache Commons Lang StringEscapeUtils,特别是StringEscapeUtils.escapeXML,它应该可以满足您的需求。

于 2013-09-18T10:09:24.380 回答