regex - 如何将 textarea 标签与特定属性匹配?

标签 regex ruby

我只想匹配具有特定属性的 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/

相关文章:

ruby - 存储类别的数据模型(多个父节点)

ruby - 我如何在 Ruby 中引用函数?

ruby - 仅从 Ruby 中的数组中选取随机元素

regex - 无法使用正则表达式在两个逗号和一个单词之间进行选择

regex - 不包含101的正则表达式

mysql - MySQL 中的正则表达式被误解

php - 替换两个字符之间的每个实例

PHP 去除字符串中的所有括号

ruby - 从/到 JSON API 对象化 Ruby 哈希

ruby-on-rails - 我的 ubuntu 用户无法访问开发用户在 postgres for rails 中创建的数据库