【问题标题】:Alter string using regex in Java在 Java 中使用正则表达式更改字符串
【发布时间】:2013-06-18 17:30:54
【问题描述】:

我有一个 XML 文件加载到这样的字符串中

<children name="{content.type}">
    <values>{video}</values>
</children>
<children name="{content.size}">
    <values>250</values>
</children>
<children name="uploaded by">
    <values>user1</values>
</children>

我想删除名称标签中的 {},使输出看起来像这样

<children name="content.type">
    <values>{video}</values>
</children>
<children name="content.size">
    <values>250</values>
</children>
<children name="uploaded by">
    <values>user1</values>
</children>

目前我有这个代码 -

Pattern p = Pattern.compile("([^,]*)\"\\{([^,]*)\\}\"([^,]*)");
Matcher m = p.matcher(content);
if (m.find()){
    System.out.println(m.group(1));
}

但是字符串在中途被切断了。我的正则表达式有问题吗?

【问题讨论】:

  • 不需要连接第二组和第三组吗?我认为您现在只打印第一个捕获的组。
  • 哈哈我觉得自己像个白痴。感谢收看这个!

标签: java regex replace


【解决方案1】:

怎么样

content.replaceAll("\\bname=\"\\{([^}]+)\\}\"", "name=\"$1\"")

【讨论】:

    【解决方案2】:

    这行得通吗?

    s.replaceAll( "name=\"\\{", "name=\"" ).replaceAll( "\\}\">", "\">" )
    

    【讨论】:

    • 只有当 OP 在他的输入中没有其他属性(如&lt;children name="{content.type}" someOtherAttrib="{some.value}"&gt;)时,这才有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2017-10-23
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多