右括号的递归正则表达式



我正在尝试用 ruby 编写一个正则表达式,以匹配以下条件的模式

/{{d+}}/双花括号,里面有一个数字

/.*{{d+}}.*/它可以在前面或后面跟任意数量的字符

/.*{{d+}}.*m/可以是多行

直到这部分它正在工作

它接受像"afaf{{}}{{"这样的字符串,所以我做了一些更改

/(?:(.*{{d+}}.*)g<1>m)/可以有多个*{{number}}*

例如。

empty string
xyz
{{345345}}
any thing{{234234324}}
<abc>{{234234}}<-
any chars{{234}}
{{234234}}any chars
{{4}}

无效的

{{non intgers}}
{{5345345}}{{
}}3345345{{
{345345}
{{34534}
}
4545
{234234
{{
5345
}}

但它没有按预期工作。

您似乎不需要递归,只需使用分组结构否定字符类来确保您不匹配不允许的字符:

rx = /A(?:[^d{}]*{{d+}})*[^d{}]*z/

  • A- 字符串的开头
  • (?:[^d{}]*{{d+}})*- 零个或多个序列:
    • [^d{}]*- 除数字、{}以外的任何 0 个或多个字符
    • {{d+}}-{{, 1+ 位数字,}}
  • [^d{}]*- 除数字、{}以外的任何 0 个或多个字符
  • z- 字符串的结尾。

请参阅 Ruby 演示测试:

rx = /A(?:[^d{}]*{{d+}})*[^d{}]*z/
ss = ['', 'xyz', '{{345345}}','any thing{{234234324}}','<abc>{{234234}}<-',"any chars{{234}}n{{234234}}any charsn{{4}}n" ]
puts "Valid:"
for s in ss
puts "#{s} => #{(s =~ rx) != nil}"
end
nonss = ['{{non intgers}}','{{5345345}}{{','}}3345345{{','{345345}',"{{34534}n}", '4545', '{234234', "{{n5345n}}" ]
puts "Invalid:"
for s in nonss
puts "#{s} => #{(s =~ rx) != nil}"
end

输出:

Valid:
=> true
xyz => true
{{345345}} => true
any thing{{234234324}} => true
<abc>{{234234}}<- => true
any chars{{234}}
{{234234}}any chars
{{4}}
=> true
Invalid:
{{non intgers}} => false
{{5345345}}{{ => false
}}3345345{{ => false
{345345} => false
{{34534}
} => false
4545 => false
{234234 => false
{{
5345
}} => false

试试这个:

(?m)^(?:(?:.+)?(?:{{)(?<NUM>d+)(?:}})(?:.+)?)$

在 https://regex101.com/r/WIuDhw/1/进行测试

最新更新