【发布时间】:2012-12-13 18:03:20
【问题描述】:
我有一个包含一些值的字符串,如下所示。我想用一些新文本替换包含特定 customerId 的 html img 标签。我尝试了没有给我预期输出的小型 java 程序。这是程序信息
我的输入字符串是
String inputText = "Starting here.. <img src=\"getCustomers.do?custCode=2&customerId=3334¶m1=123/></p>"
+ "<p>someText</p><img src=\"getCustomers.do?custCode=2&customerId=3340¶m2=456/> ..Ending here";
正则表达式是
String regex = "(?s)\\<img.*?customerId=3340.*?>";
我想放入输入字符串的新文本
编辑开始:
String newText = "<img src=\"getCustomerNew.do\">";
编辑结束:
现在我在做
String outputText = inputText.replaceAll(regex, newText);
输出是
Starting here.. Replacing Text ..Ending here
但我的预期输出是
Starting here.. <img src=\"getCustomers.do?custCode=2&customerId=3334¶m1=123/></p><p>someText</p>Replacing Text ..Ending here
请注意,在我的预期输出中,只有包含 customerId=3340 的 img 标签被替换为替换文本。我不明白为什么在输出中我得到两个 img 标签都被替换了?
【问题讨论】:
-
您正在使用 regex 解析 html,但它永远不会完全正常工作(这通常是对 regex 的限制,而不是您的 regexing 技能)
-
你使用了错误的工具..使用 html 解析器
-
@ Some1.Kill.The.DJ 你能帮我如何使用像 jsoup 这样的 html 解析器获得预期的结果吗?
-
M Sach,您可以查看我的答案,了解 jsoup 工作的完整示例。
标签: java regex string string-matching