java - 如何在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));
}
解决方案
您可以匹配括号之间的字符串,然后用管道拆分其中的文本并使用以下方法动态构建替换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.
推荐阅读
- laravel - 有没有办法通过命令行在 laravel 中制作服务容器文件?
- javascript - 如何使用 vanilla javascript 根据值更改 td 元素的背景和字体颜色
- python - 需要解析多行多列字符之间的子串
- arrays - 如何检测并发日期
- python - 编辑距离算法特刊
- javascript - Javascript按位运算
- tensorflow - 我无法在张量板上看到任何东西。如何解决这个问题?
- oracle - 安装 Oracle 客户端工具 - Docker、Roundhouse、Oracle
- types - 创建一个抽象类型作为不同函数的包装器
- javascript - 在 API 结果之后定义变量时遇到问题