gpt4 book ai didi

ruby - 正则表达式获取括号之间的值

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:54 25 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来获取括号之间的值。我期望一个没有括号的值。例如,给定:

value = "John sinu.s(14)" 

我希望得到 14

我尝试了以下方法:

value[/\(.*?\)/]

但它给出了结果 (14)。请帮助我。

最佳答案

你可以使用

value[/\((.*?)\)/, 1]

value[/\(([^()]*)\)/, 1]

使用 capturing group以及仅提取组值的第二个参数。

注意 \((.*?)\) 也会匹配其中包含 ( 字符的子串,而第二个选项只会匹配介于不包含 () 的括号,因为 [^()] 是一个 negated character class 匹配除 ()

参见 Ruby demo online .

来自Ruby docs :

str[regexp, capture] → new_str or nil
If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

如果您需要提取多次出现,请使用 String#scan:

value = "John sinu.s(14) and Jack(156)"
puts value.scan(/\(([^()]*)\)/)
# => [ 14, 156 ]

参见 another Ruby demo .

关于ruby - 正则表达式获取括号之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49647692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com