I have strings:
до 100(прошло до 15 лет)
до 100 (прошл开发者_开发知识库о от 15 лет)
до 75
до 100 (10 лет)
до 100 (10 лет)
I want to cut strings like
до 100
до 100
до 75
до 100
до 100
strings = ['до 100(прошло до 15 лет)',
'до 100 (прошло от 15 лет)',
'до 75',
'до 100 (10 лет)',
'до 100 (10 лет)']
strings.map! { |str| str[/до \d+/] }
p strings #=> ["до 100", "до 100", "до 75", "до 100", "до 100"]
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.
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.
精彩评论