我需要使用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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句