【问题标题】:Recursive regex for closed parenthesis闭括号的递归正则表达式
【发布时间】:2019-03-13 23:18:10
【问题描述】:

我正在尝试将 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
}}

但它没有按预期工作。

【问题讨论】:

  • 字符串可以包含独立的{}吗?如果没有,请尝试/\A(?:[^{}]*{{\d+}})*[^{}]*\z/
  • no { 后跟 {,并用 }} 正确关闭
  • 您能举个例子说明一下吗?请添加到问题正文中。请检查rubular.com/r/EuBB1IXqMH 是否有效。
  • 它是如此接近唯一的问题是它接受独立{或} {{234234}}}这个无效
  • 伟大的工作,它的工作原理补充说,在答案中,我会再推荐一件事如何在分组和递归中变得更好:)

标签: ruby regex


【解决方案1】:

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

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

详情

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

Ruby demo test

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

nonss = ['{{non intgers}}','{{5345345}}{{','}}3345345{{','{345345}',"{{34534}\n}", '4545', '{234234', "{{\n5345\n}}" ]
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

【讨论】:

    【解决方案2】:

    试试这个:

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

    https://regex101.com/r/WIuDhw/1/测试

    【讨论】:

    • "{{213123}}{{" 这不应该是有效的字符串
    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多