【发布时间】:2019-08-09 20:50:11
【问题描述】:
有人可以分解这个正则表达式匹配的内容吗?
Regex.Match("<a>", "^<([a-zA-Z][a-zA-Z0-9]*)( [^>]*)?>$")
【问题讨论】:
-
Regex101 是了解特定正则表达式在做什么的好工具。
-
感谢您的建议!
有人可以分解这个正则表达式匹配的内容吗?
Regex.Match("<a>", "^<([a-zA-Z][a-zA-Z0-9]*)( [^>]*)?>$")
【问题讨论】:
给你,解释和格式化
^ # The beginning of the string BOS
< # A literal '<'
( # (1 start), Capture group 1
[a-zA-Z] # Start with a letter
[a-zA-Z0-9]* # 0 or more letter or number
) # (1 end)
( # (2 start) Optional Capture group 2
[^>]* # 0 or more, non '>' character
)? # (2 end)
> # A literal '>'
$ # The end of the string EOS
一个忠告,这个结构有它的位置([^>]*)?
但应该写成([^>]*?)。
【讨论】:
[^>]*前面有个空格,所以( [^>]*)?不能替换成([^>]*?)。
[^>] 匹配了一个空格。但我不认为他实际上需要一个空间才能匹配,因为它是可选的。但是,也许……但我对此表示怀疑。应该是笔误!!
>或什么都没有。 OP 匹配 <tag attr="blah"> 但你的匹配 <tagattr="blah">
^<([a-zA-Z][a-zA-Z0-9]*)(?=[ ]|>)([^>]*?)>$ 匹配 <tag attr="blah"> 或 <tag > 或 <tag> 但不匹配 <tagattr="blah">
<[\w:]+(?=\s|/?>)((?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+)>