如何用红宝石切割弦

Vya*_*nov 2 ruby regex string

我有字符串:

?? 100(?????? ?? 15 ???)
?? 100 (?????? ?? 15 ???)
?? 75
?? 100 (10 ???)
?? 100 (10 ???)
Run Code Online (Sandbox Code Playgroud)

我想剪切字符串

?? 100
?? 100
?? 75
?? 100
?? 100
Run Code Online (Sandbox Code Playgroud)

Vic*_*gin 7

strings = ['?? 100(?????? ?? 15 ???)',
           '?? 100 (?????? ?? 15 ???)',
           '?? 75',
           '?? 100 (10 ???)',
           '?? 100 (10 ???)']

strings.map! { |str| str[/?? \d+/] }

p strings    #=> ["?? 100", "?? 100", "?? 75", "?? 100", "?? 100"]
Run Code Online (Sandbox Code Playgroud)


Mat*_*chu 6

有几种不同的方法.例如,(如果字符串有一个字符串,则可以从第一个字符串开始剪切字符串.但是,我喜欢这种更明确的正则表达式方法:

regex = /^?? \d+/
str = "?? 100(?????? ?? 15 ???)"
result = str[regex] # "?? 100"
Run Code Online (Sandbox Code Playgroud)

正则表达式/^?? \d+/匹配??在字符串开头出现的实例和一系列数字.语法str[regex]返回第一个(在这种情况下,仅)匹配,或者nil如果没有匹配.


Cho*_*ett 5

怎么样的:

cut = full.match(/^?? \d*/)[0]
Run Code Online (Sandbox Code Playgroud)

...也就是说,匹配锚定到字符串开头的字符??,后跟任意数量的数字; 返回整个匹配的部分.