如何用ruby切割字符串

时间:2021-06-19 16:01:08

I have strings:

我有字符串:

до 100(прошло до 15 лет)
до 100 (прошло от 15 лет)
до 75
до 100 (10 лет)
до 100 (10 лет)

I want to cut strings like

我想剪断一些线

до 100
до 100
до 75
до 100
до 100

3 个解决方案

#1


7  

strings = ['до 100(прошло до 15 лет)',
           'до 100 (прошло от 15 лет)',
           'до 75',
           'до 100 (10 лет)',
           'до 100 (10 лет)']

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

p strings    #=> ["до 100", "до 100", "до 75", "до 100", "до 100"]

#2


6  

There are a few different approaches to this. For example, you could cut off the string starting at the first (, if the string has one. However, I like this more explicit regular expression approach:

对此有几种不同的方法。例如,可以从第一个(如果字符串有一个的话)开始切断字符串。然而,我喜欢这种更明确的正则表达式方法:

regex = /^до \d+/
str = "до 100(прошло до 15 лет)"
result = str[regex] # "до 100"

The regular expression /^до \d+/ matches instances of до and a series of digits that occur at the start of the string. The syntax str[regex] returns the first (and, in this case, only) match, or nil if there is no match.

正则表达式/ ^до\ d + /匹配的实例до和一系列的数字,出现在字符串的开始。语法str[regex]返回第一个匹配项(在本例中为唯一匹配项),如果没有匹配项,返回nil。

#3


5  

How about something like:

如何像:

cut = full.match(/^до \d*/)[0]

...that is, match anchored to start of the string the characters до, followed by any number of digits; return the whole matched part.

…即匹配固定字符串的字符до开始,紧随其后的是任意数量的数字;返回整个匹配的部分。

#1


7  

strings = ['до 100(прошло до 15 лет)',
           'до 100 (прошло от 15 лет)',
           'до 75',
           'до 100 (10 лет)',
           'до 100 (10 лет)']

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

p strings    #=> ["до 100", "до 100", "до 75", "до 100", "до 100"]

#2


6  

There are a few different approaches to this. For example, you could cut off the string starting at the first (, if the string has one. However, I like this more explicit regular expression approach:

对此有几种不同的方法。例如,可以从第一个(如果字符串有一个的话)开始切断字符串。然而,我喜欢这种更明确的正则表达式方法:

regex = /^до \d+/
str = "до 100(прошло до 15 лет)"
result = str[regex] # "до 100"

The regular expression /^до \d+/ matches instances of до and a series of digits that occur at the start of the string. The syntax str[regex] returns the first (and, in this case, only) match, or nil if there is no match.

正则表达式/ ^до\ d + /匹配的实例до和一系列的数字,出现在字符串的开始。语法str[regex]返回第一个匹配项(在本例中为唯一匹配项),如果没有匹配项,返回nil。

#3


5  

How about something like:

如何像:

cut = full.match(/^до \d*/)[0]

...that is, match anchored to start of the string the characters до, followed by any number of digits; return the whole matched part.

…即匹配固定字符串的字符до开始,紧随其后的是任意数量的数字;返回整个匹配的部分。