我需要使用java在2个特定单词之间匹配并替换反斜杠\为正斜杠/。我尝试过这个,它在正则表达式测试器 https://regexr.com/474s0 中工作正常但当我从基于 java 的应用程序进行测试时不起作用;出现此错误。
org.apache.oro.text.regex.MalformedPatternException:序列(?<...)无法识别
正则表达式尝试: (?<=<(DocumentImagePath)>.*?)(\\)(?=.*<\/(DocumentImagePath)>)
示例:
<DocumentImagePath>95230-88\M0010002F.tif\test</DocumentImagePath>
<DocumentImagePath>123-88\M0010002F.tif\test</DocumentImagePath>
<DocumentImagePath>abc-88\M0010002F.tif\test</DocumentImagePath>
感谢任何帮助。
注意:我知道并非所有编译器都支持正向查找,但正在寻找适用于 Java 的合适替代正则表达式。
最佳答案
你可以这样做(Java 9+):
String sample = "<DocumentImagePath>95230-88\\M0010002F.tif\\test</DocumentImagePath>\r\n" +
"95230-88\\M0010002F.tif\\test\r\n" +
"<DocumentImagePath>123-88\\M0010002F.tif\\test</DocumentImagePath>\r\n" +
"<DocumentImagePath>abc-88\\M0010002F.tif\\test</DocumentImagePath>\r\n";
String result = Pattern.compile("<DocumentImagePath>.*?</DocumentImagePath>")
.matcher(sample)
.replaceAll(r -> r.group().replace('\\', '/'));
System.out.println(result);
输出
<DocumentImagePath>95230-88/M0010002F.tif/test</DocumentImagePath>
95230-88\M0010002F.tif\test
<DocumentImagePath>123-88/M0010002F.tif/test</DocumentImagePath>
<DocumentImagePath>abc-88/M0010002F.tif/test</DocumentImagePath>
更新:对于 Java 8 及更早版本,请使用以下代码:
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("<DocumentImagePath>.*?</DocumentImagePath>").matcher(sample);
while (m.find())
m.appendReplacement(buf, m.group().replace('\\', '/'));
String result = m.appendTail(buf).toString();
关于java - 正则表达式匹配 2 个字符串中的所有匹配项 + Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54371524/