首页 > 解决方案 > 如何在java中使用正则表达式来操作字符串

问题描述

String s = "My cake should have ( sixteen | sixten | six teen ) candles, I love and ( should be | would be ) puff them."

最终更改的字符串

My cake should have <div><p id="1">sixteen</p><p  id="2">sixten</p><p  id="3">six teen</p></div>  candles, I love and <div><p  id="1">should be</p><p  id="2"> would be</p> puff them

我试过的是用这个


Pattern pattern = Pattern.compile("\\(\\s*(.*?)(?=\\s*\\))");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1)); 
}

标签: javaregex

解决方案


您可以匹配括号之间的字符串,然后用管道拆分其中的文本并使用以下方法动态构建替换Matcher.appendReplacement

String s = "My cake should have ( sixteen | sixten | six teen ) candles, I love and ( should be | would be ) puff them.";
String rx = "\\(([^()]*)\\)";
        
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile(rx).matcher(s);
while (m.find()) {
    String add = "";
    String[] items = m.group(1).split("\\|");
    for (int i=1; i<=items.length; i++) {
        add += "<p id=\"" + i + "\">" + items[i-1].trim() + "</p>";
    }
    m.appendReplacement(result, "<div>"+add+"</div>");
}
m.appendTail(result);
System.out.println(result.toString());

请参阅Java 在线演示。输出:

My cake should have <div><p id="1">sixteen</p><p id="2">sixten</p><p id="3">six teen</p></div> candles, I love and <div><p id="1">should be</p><p id="2">would be</p></div> puff them.

推荐阅读