Ruby中如何提取大写R后最多两位的目标整数
问题描述
有以下Ruby字符串:
x = '4x4 @ 32" hjy w/ R43 potter'
x = '4x4 @ 32" hjy w/ R4 26 potter'
x = 'Restful4 4 @ 32" hjy R8 26 potter'
需要提取大写字母R后面的连续数字,即第一个字符串中的43、第二个中的4、第三个中的8。已知字符串中必有大写R。
尝试用index('R')实现时需要处理多种情况,十分繁琐;尝试用match方法时写了如下代码,但运行报错:
sFind = x.match /(?<name>R \d+) / debug=debug+sFind[:name].to_s + "\n"
解决思路
你之前的正则问题在于:强制要求R后面必须有空格,且数字后面也要有空格,但实际场景中R和数字之间可能没有空格(比如R43、R8),导致匹配失败,sFind为nil,调用[:name]自然报错。
正确的正则需要兼容R和数字之间有/无空格的情况,同时精准捕获R后的连续数字:
R:匹配大写字母R\s?:匹配0个或1个空格(处理两种空格情况)(\d+):捕获1位及以上的连续数字(这就是我们要的结果)
代码实现
# 测试字符串 str1 = '4x4 @ 32" hjy w/ R43 potter' str2 = '4x4 @ 32" hjy w/ R4 26 potter' str3 = 'Restful4 4 @ 32" hjy R8 26 potter' # 提取R后数字的方法 def get_r_following_num(str) # 匹配并捕获目标数字 match_data = str.match(/R\s?(\d+)/) # 返回捕获到的数字(因题目说明必有R,所以match_data不会为nil) match_data[1] end # 测试输出 puts get_r_following_num(str1) # => 43 puts get_r_following_num(str2) # => 4 puts get_r_following_num(str3) # => 8
如果想用命名捕获组,也可以这么写:
match_data = str.match(/R\s?(?<r_num>\d+)/) puts match_data[:r_num] # 直接输出数字
内容的提问来源于stack exchange,提问作者jay
相关产品推荐
相关产品推荐

