我试图以最优雅的方式剥离和替换看起来如下的文本字符串:
element {"item"} {text {
} {$i/child::itemno}
看起来像:
<item> {$i/child::itemno}
因此删除元素文本替换其大括号并删除文本及其随附的大括号。
我认为适当的正则表达式是:
/element\s*\{"([^"]+)"\}\s*{text\s*{\s*}\s*({[^}]*})/
但我不确定在java中使用的反斜杠的数量,以及如何完成使用我的组(1)的最终替换,并将其替换为&lt;在它的开始和&gt;最后:
到目前为止,我有这个(虽然我可能会因为完全重写而感觉更好?)
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的每个实例,请将其替换为&lt; &GT;在开始
我想我遇到了一个问题。我想做的事情比我之前说的要难。通过以下解决方案:
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>
答案 0 :(得分:3)
\s
变为\\s
; {
都需要转义:\\{
,}
不需要逃避(尽管如果你逃脱它们也不会受到伤害)。尝试:
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}