Java Regex – 如何替换模式或如何替换模式
我有一堆
HTML文件.在这些文件中,我需要更正IMG标记的src属性.
IMG标签通常看起来像这样: <img alt="" src="./Suitbert_files/233px-Suitbertus.jpg" class="thumbimage" height="243" width="233" />` 其中属性不是任何特定顺序. <img alt="" src="Suitbert%20%E2%80%93%20Wikipedia_files/233px-Suitbertus.jpg" class="thumbimage" height="243" width="233" /> 到目前为止,我有以下课程: import java.util.regex.*; public class Replacer { // this PATTERN should find all img tags with 0 or more attributes before the src-attribute private static final String PATTERN = "<img.*ssrc="./"; private static final String REPLACEMENT = "<img.*ssrc=""; private static final Pattern COMPILED_PATTERN = Pattern.compile(PATTERN,Pattern.CASE_INSENSITIVE); public static void findMatches(String html){ Matcher matcher = COMPILED_PATTERN.matcher(html); // Check all occurance System.out.println("------------------------"); System.out.println("Following Matches found:"); while (matcher.find()) { System.out.print("Start index: " + matcher.start()); System.out.print(" End index: " + matcher.end() + " "); System.out.println(matcher.group()); } System.out.println("------------------------"); } public static String replaceMatches(String html){ //Pattern replace = Pattern.compile("s+"); Matcher matcher = COMPILED_PATTERN.matcher(html); html = matcher.replaceAll(REPLACEMENT); return html; } } 所以,我的方法findMatches(String html)似乎正确找到src属性以./开头的所有IMG标记. 现在我的方法replaceMatches(String html)没有正确地替换匹配. 解决方法
试试这些:
PATTERN = "(<img[^>]*ssrc=")./" REPLACEMENT = "$1" 基本上,你捕获除组#1中的./之外的所有内容,然后使用$1占位符将其重新插入,有效地剥离./. 请注意我是如何将.*更改为[^>] *的.如果在同一行上碰巧有两个IMG标签,如下所示: <img src="good" /><img src="./bad" /> …你的正则表达式会匹配这个: <img src="good" /><img src="./ 即使你使用非贪婪的话也会这样做.*? [^>;] *确保匹配始终包含在一个标记内. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |