披露:我已阅读 this answer很多次在这里,我知道比使用正则表达式来解析 HTML 更好。这个问题只是为了扩大我对正则表达式的了解。
说我有这个字符串:
some text <tag link="fo>o"> other text
我想匹配整个标签,但如果我使用
<[^>]+>
它只匹配 <tag link="fo>
.我如何确保
>
引号内可以忽略。我可以轻松地编写一个带有 while 循环的解析器来执行此操作,但我想知道如何使用正则表达式来执行此操作。
最佳答案
正则表达式:
<[^>]*?(?:(?:('|")[^'"]*?\1)[^>]*?)*>
在线演示:
http://regex101.com/r/yX5xS8
完整说明:
我知道这个正则表达式可能让人头疼,所以这是我的解释:
< # Open HTML tags
[^>]*? # Lazy Negated character class for closing HTML tag
(?: # Open Outside Non-Capture group
(?: # Open Inside Non-Capture group
('|") # Capture group for quotes, backreference group 1
[^'"]*? # Lazy Negated character class for quotes
\1 # Backreference 1
) # Close Inside Non-Capture group
[^>]*? # Lazy Negated character class for closing HTML tag
)* # Close Outside Non-Capture group
> # Close HTML tags
关于RegEx:如果某个字符在引号内,则不匹配它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164374/