我只想将textarea标签与某个属性匹配。鉴于我有这个字符串:
{{one}}
<div>{{two}}</div>
<textarea data-match-this="true">{{three}}</textarea>
<textarea>{{four}}</textarea>
{{five}}
我目前有这个正则表达式:
({{(?!#|\/).*?}})(?!<textarea>)(?!<\/textarea\>)
除文本区域内的标签外,当前与所有标签匹配。我可以使用什么正则表达式来使其与textarea中具有“ data-match-this ='true'”属性的标签匹配?
答案 0 :(得分:3)
您会这样做
/<textarea(?=\s)(?=(?:[^>"']|"[^"]*"|'[^']*')*?\sdata-match-this\s*=\s*(?:(['"])\s*true\s*\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+>([\S\s]*?)<\/textarea\s*>/
https://regex101.com/r/Oy6vQd/1
内容在第2组中。
注意-搜索的属性/值的位置
是独立的,可以在标记中的任何位置。
解释
# Begin open textarea tag
< textarea
(?= \s )
(?= # Asserttion (a pseudo atomic group)
(?: [^>"'] | " [^"]* " | ' [^']* ' )*?
\s data-match-this \s* = \s*
(?:
( ['"] ) # (1), Quote
\s* true \s* # data-match-this = true
\1
)
)
# Have the data-match-this = true,
# just match the rest of tag
\s+
(?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]? )+
> # End span tag
( [\S\s]*? ) # (2), textarea content
</textarea \s* > # Close textarea tag
答案 1 :(得分:1)
我只能使用data-match-this='true'
来匹配textarea标签(包括带有类的标签和没有内容的标签)
正则表达式:<textarea.*data-match-this="true".*>.*<\/textarea>
。如果需要捕获内容,只需添加一些括号即可,例如:<textarea.*data-match-this="true".*>(.*)<\/textarea>
。要使其仅获取带有内容的标签,请将最后一个.*
更改为.+
:<textarea.*data-match-this="true".*>.+<\/textarea>
答案 2 :(得分:1)