在Java中我需要匹配 <a>没有href属性的字符串标记.例如,在以下字符串中:
text <a class="aClass" href="#">link1</a> text <a class="aClass" target="_blank">link2</a> text
Run Code Online (Sandbox Code Playgroud)
它不应该匹配<a class="aClass" href="#">link1</a>(因为它包含href)但它应该匹配<a class="aClass" target="_blank">link2</a>(因为它不包含href).
我设法构建RegEx以匹配我的标签:
<a[^>]*>(.*?)</a>
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何用href消除标签
(我知道我可以使用HTML解析器等,但我需要使用RegEx执行此操作.
Ro *_* Mi 24
注意正则表达式,<a[^>]*因为这些也将匹配其他有效的html标签,这些标签a以<abbr>or或者开头<address>.另外简单地查找字符串的存在href是不够好的,因为该字符串可能在另一个属性的值内<a class="thishrefstuff"...,或者像或者是另一个属性的一部分,如<a hreflang="en"...
这个表达式将:
<a... </a>不包含href属性.a,而不是一个标签,该标签简单地用字母开头a像<address>href嵌入在属性名称中的子字符串,如有效hreflang='en'或组成Attributehref="some value".bogus='href=""'<a(?=\s|>)(?!(?:[^>=]|=(['"])(?:(?!\1).)*\1)*?\shref=['"])[^>]*>.*?<\/a>

<a(?=\s|>)匹配open标签并确保标签名称后面的空格或紧密括号,这会强制名称a而不是其他名称(?! 如果我们在此标记中找到一个href,那么这个类型的标记不是我们正在寻找的标记
(?: 启动非捕获组以遍历标记内的所有字符[^>=] 匹配阻止正则表达式引擎离开标记的所有非标记关闭字符,以及阻止引擎继续盲目匹配所有字符的非等号| 要么 =(['"])匹配等号后跟开放的双引号或单引号.引用被捕获到组2中,以便以后可以正确配对(?:(?!\1).)* 匹配所有不是与开放引用匹配的近引号的字符 \1 匹配正确的关闭报价)*? 关闭非捕获组,并根据需要重复,直到\shref=['"]匹配所需的href属性.在\s和=["']确保属性名称就是HREF) 关闭负向前瞻[^>]*>.*?<\/a> 匹配整个字符串从打开到关闭输入文本
<abbr>RADIO</abbr> text <a class="aClass" href="#">link1</a> text <a bogus='href=""' class="aClass" target="_blank">link2</a> text
码
如果您希望在替换函数中使用它来删除非href-anchor标记,那么只需替换所有匹配项.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
public static void main(String[] asd){
String sourcestring = "source string to match with pattern";
Pattern re = Pattern.compile("<a(?=\\s|>)(?!(?:[^>=]|=(['\"])(?:(?!\\1).)*\\1)*?\\shref=['\"])[^>]*>.*?<\\/a>
",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = re.matcher(sourcestring);
int mIdx = 0;
while (m.find()){
for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
System.out.println( "[" + mIdx + "][" + groupIdx + "] = " + m.group(groupIdx));
}
mIdx++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
火柴
$matches Array:
(
[0] => Array
(
[0] => <a bogus='href=""' class="aClass" target="_blank">link2</a>
)
[1] => Array
(
[0] =>
)
)
Run Code Online (Sandbox Code Playgroud)
我觉得你需要用正则表达式来做这件事很奇怪,但你可以使用负前瞻。
<a(?![^>]+href).*?>(.*?)</a>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18363 次 |
| 最近记录: |