【发布时间】:2014-12-03 17:55:06
【问题描述】:
我正在尝试在特定场景中使用正则表达式,如下所述:
有许多 HTML 页面,每个页面都包含多个具有动态值的 <img src> 标签:
Tag1 = <p>Para1 <img src="/A/images/b.txt">Some text</p>
Tag2 = <p>Para2 <img src="/A/B/images/c.jpeg">Some text</p>
Tag3 = <p>Para3 <img src="/../images/H/e.png">Some text</p>
Tag4 = <p>Para4 <img src="/../D/images/G/J/f.gif">Some text</p>
我们的目标是模式"/<anything>/images/。更换后我们需要的是
Tag1 = <p>Para1 <img src="/library/MYFOLDER/location/b.txt">Some text</p>
Tag2 = <p>Para2<img src="/library/MYFOLDER/location/c.jpeg">Some text</p>
Tag3 = <p>Para3<img src="/library/MYFOLDER/location/H/e.png">Some text</p>
Tag4 = <p>Para4<img src="/library/MYFOLDER/location/G/J/f.gif">Some text</p>
实际发生的情况非常不同。模式是在/images 之后吃掉所有东西并给我们
Tag1 = <p>Para1 <img src="/library/MYFOLDER/locationp>
Tag2 = <p>Para2<img src="/library/MYFOLDER/locationp>
Tag3 = <p>Para3<img src="/library/MYFOLDER/locationp>
Tag4 = <p>Para4<img src="/library/MYFOLDER/locationp>
这是我正在使用的正则表达式模式
"{1}(.){1,}[/images/]{1}<br>
代码如下:
String subStringTem = "<p><strong>Control Steps:</strong> <img src=\"../images/retain_image.gif\" width=\"20\" > Description.</p>";
String newImagPath = "\"/library/MYFOLDER/location";
final Pattern p = Pattern.compile("\"{1}(.){1,}[/images/]{1}");
final Matcher m = p.matcher(subStringTem);
String result = m.replaceAll(newImagPath);
System.out.println(result);
预期结果:
<p><strong>Control Steps:</strong> <img src="/library/MYFOLDER/location/retain_image.gif\" width=\"20\" > Description.</p>
实际结果:
<p><strong>Control Steps:</strong> <img src="/library/MYFOLDER/locationp>
【问题讨论】:
-
[/images/]在正则表达式中匹配 一个 字符,即/、i、m、a、g、e,或s(最后一个 / 是多余的)。如果要匹配序列,请删除方括号。此外,正则表达式中永远不需要{1},{1,}更简洁地表示为+。我认为您应该查看有关正则表达式的教程,例如this one。