我想匹配以下字符串:带字符串匹配:https://apidock.com/ruby/string/string/match
"The account 340394034 is finalized"
"The account 9394834 is finalized"
"The account 12392039483 is finalized"
"The account 3493849384 is finalized"
"The account 32984938434983 is finalized"
我必须使用哪个正则符合此字符串与其中的数字占位符?谢谢
"The account {number_placeholder} is finalized"
这是完整的正则
d+
根据输入的不同,假设字符串中有其他数字,您可以使用它并获取捕获组1的内容:
accounts+(d+)
如果您只想使用match
方法来确定给定字符串是否匹配示例中的模式,则可以执行此操作:
example = "The account 32984938434983 is finalized"
if example.match(/The account d+ is finalized/)
puts "it matched"
else
puts "it didn't match"
end
匹配方法返回一个 MatchData
对象(基本上是与正则匹配的字符串的一部分,在这种情况下,这是整个事情)。在非匹配字符串上使用它将返回nil
,这意味着您可以将匹配方法的结果用于IF-Statement。
如果要在字符串中提取数字,则只有在字符串与模式匹配时,您可以执行此操作:
example = "The account 32984938434983 is finalized"
match_result = example.match(/The account (d+) is finalized/)
number = if match_result
match_result.captures.first.to_i
else
number = nil # or 0 / some other default value
end
正则括号形成一个"捕获组"。结果上的captures
方法给出了所有捕获组匹配的数组。first
方法从该数组获取第一个(仅在这种情况下)元素,并且to_i
方法将字符串转换为整数。