【发布时间】: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 我可能把这个问题弄得太复杂了