正则表达式匹配 2 个字符串 + Java 中的所有出现

我需要使用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 的合适替代正则表达式。


宝慕林4294392
浏览 173回答 1
1回答

慕妹3242003

你可以这样做(Java 9+):String sample = "<DocumentImagePath>95230-88\\M0010002F.tif\\test</DocumentImagePath>\r\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "95230-88\\M0010002F.tif\\test\r\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "<DocumentImagePath>123-88\\M0010002F.tif\\test</DocumentImagePath>\r\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "<DocumentImagePath>abc-88\\M0010002F.tif\\test</DocumentImagePath>\r\n";String result = Pattern.compile("<DocumentImagePath>.*?</DocumentImagePath>")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.matcher(sample)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.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())&nbsp; &nbsp; m.appendReplacement(buf, m.group().replace('\\', '/'));String result = m.appendTail(buf).toString();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java