【问题标题】:regex and substitution in javajava中的正则表达式和替换
【发布时间】:2010-01-20 17:42:49
【问题描述】:

我正在尝试以最优雅的方式剥离和替换如下所示的文本字符串:

element {"item"} {text { 
          } {$i/child::itemno} 

看起来像:

<item> {$i/child::itemno} 

因此删除元素文本替换其大括号并删除文本及其随附的大括号。

我认为合适的正则表达式是:

/element\s*\{"([^"]+)"\}\s*{text\s*{\s*}\s*({[^}]*})/

但我不确定在 java 中使用的反斜杠的数量以及如何完成使用我的 group(1) 的最终替换并将其替换为 在其结尾:

到目前为止,我有这个(尽管完全重写可能会更好?)

 Pattern p = Pattern.compile("/element\\s*\\{\"([^\"]+)\"\\}\\s*{text\\s*{\\s*}\\s*({[^}]*})/ "); 
             // Split input with the pattern 
        Matcher m = p.matcher("element {\"item\"} {text {\n" + 
                "          } {$i/child::itemno} text { \n" + 
                "            } {$i/child::description} text {\n" + 
                "            } element {\"high_bid\"} {{max($b/child::bid)}}  text {\n" + 
                "        }}  "); 

// 接下来对第1组的每个实例,在开头用替换


我想我偶然发现了一个问题。我想做的事情比我之前说的要难一些。使用以下解决方案:


element {"item"} {text { } {$i/child::itemno} text { } {$i/child::description} text { } element {"high_bid"} {{max($b/child::bid)}} text { }}
给:
<item> {$i/child::itemno} text { } {$i/child::description} text { } element {"high_bid"} {{max($b/child::bid)}} text { }}

如我所料:

<item>{$i/child::itemno}{$i/child::description}<high_bid>{fn:max($b/child::bid)}</high_bid></item>

【问题讨论】:

  • 这会非常非常痛苦。
  • 不一定是 :P 我可能把这个问题弄得太复杂了

标签: java regex


【解决方案1】:
  1. Java 正则表达式的编写没有分隔符。所以丢掉正斜杠;
  2. 每一个反斜杠都需要一个额外的,所以\s变成\\s
  3. 所有{ 都需要转义:\\{} 不需要转义(尽管如果您转义它们也无妨)。

试试:

String text = "element {\"item\"} {text { } {$i/child::itemno}";
System.out.println(text.replaceAll("element\\s*\\{\"([^\"]+)\"}\\s*\\{text\\s*\\{\\s*}\\s*(\\{[^}]*})", "<$1> $2"));

输出:

<item> {$i/child::itemno} 

【讨论】:

  • 谢谢!这很有效(我认为相对无痛!)
  • 不客气。痛苦取决于您对正则表达式的熟练程度。不熟悉正则表达式的人可能会不同意您的看法。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多