【问题标题】:java replace - replace text in string between two tags that are seperated by spaces and new linejava replace - 替换由空格和换行符分隔的两个标签之间的字符串中的文本
【发布时间】:2018-05-15 10:53:42
【问题描述】:
String abc = 
"<Message>
    <Details> hello </Details>
</Message>
<Customer>
   <Details> John </Details>
</Customer>
<Bank>
  <Details> BANK1 <Details>
<Bank>"

现在我想用静态文本(例如:Peter)替换“客户/详细信息”(此处为 John)之间的字符串,即用 Peter 替换 John。如何在 java 中使用 ReplaceAll 函数 + 正则表达式来做到这一点。我不想在替换后扰乱 xml 格式的字符串格式。 预期输出

String abc = 
"<Message>
    <Details> hello </Details>
</Message>
<Customer>
   <Details> Peter</Details>
</Customer>
<Bank>
  <Details> BANK1 <Details>
<Bank>"

【问题讨论】:

  • 您确定不想使用适当的 XML 工具吗?
  • 您好,欢迎您,您介意发布您已经尝试过的minimal reproducible example 吗?
  • 我尝试过这样的事情。但是当没有 \n 或 \s(客户和详细信息标签之间没有换行符和空格时,这将起作用,但在我的情况下,它不是那样的。String str = "
    John
    "; str = str.replaceAll("(
    )[^&]*(
    )", "$1 peter $2"); System.out.println("replaced字符串:"+str);

标签: java replace


【解决方案1】:

您忘记了您正在识别的标记内的空格:

abc.replaceAll("(<Customer>\\s*<Details>)[^<]+(</Details>\\s*</Customer>)", "$1 Fred $2");

\s 字符类可识别所有空格,包括 \n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 2022-01-06
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2021-07-23
    • 2019-12-25
    相关资源
    最近更新 更多