为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2022-05-21 20:58:01
我需要使用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 的合适替代正则表达式。
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

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


查看完整回答
反对 回复 2022-05-21
  • 1 回答
  • 0 关注
  • 172 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号