如何匹配具有特定属性的textarea标签?

时间:2019-07-09 23:48:38

标签: regex ruby

我只想将textarea标签与某个属性匹配。鉴于我有这个字符串:

{{one}}

<div>{{two}}</div>

<textarea data-match-this="true">{{three}}</textarea>

<textarea>{{four}}</textarea>

{{five}}

我目前有这个正则表达式:

({{(?!#|\/).*?}})(?!<textarea>)(?!<\/textarea\>)

除文本区域内的标签外,当前与所有标签匹配。我可以使用什么正则表达式来使其与textarea中具有“ data-match-this ='true'”属性的标签匹配?

这是我的小卢:https://rubular.com/r/RuVrypBsdDVJii

3 个答案:

答案 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)

我猜想这个表达式可能会起作用,可能需要进行一些修改:

^((?=(.*?<textarea.*(data-match-this="true".*))>)|(?!(.*?<textarea.*>))).*?({{(?!#|\/).*?}}).*$
this demo右上角说明的

,如果您想进一步探索或简化/修改它,请在this link中观察它如何与某些示例输入步骤匹配如果愿意,可以逐步进行。