我只想匹配具有特定属性的 textarea 标签。鉴于我有这个字符串:
{{one}}
<div>{{two}}</div>
<textarea data-match-this="true">{{three}}</textarea>
<textarea>{{four}}</textarea>
{{five}}
我目前有这个正则表达式:
({{(?!#|\/).*?}})(?!<textarea>)(?!<\/textarea\>)
当前匹配除文本区域内的标签之外的所有标签。我可以使用什么正则表达式来使它能够将文本区域内的标签与“data-match-this='true'”属性相匹配?
这是我的 Rubular:https://rubular.com/r/RuVrypBsdDVJii
最佳答案
你会这样做
/<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
关于regex - 如何将 textarea 标签与特定属性匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961748/