在Ruby字符串中按字符匹配字符

Cod*_*ker 1 ruby string

我试图在字符串中按位置匹配数字字符.例如,在字符串中"1234567",我想选择第二个到第四个字符:"234"."D9873Y.31"也应该出现"987".你有什么建议吗?

And*_*all 5

你不需要正则表达式,你可以使用String#[]:

s = '1234567'
s[1..3]  #=> "234"

s = 'D9873Y.31'
s[1..3]  #=> "987"
Run Code Online (Sandbox Code Playgroud)