繁体   English   中英

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

[英]Regex to match all the occurences within 2 strings + 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的正则表达式替代品。

您可以这样做(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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM