Pregunta

I need to truncate part of the string which doesn't match a given pattern. Let's say the string is:

s = "Lorem ipsum dolor sit amet"

My matching pattern would be ipsum dolor and I would like to truncate all the rest, so that:

s.gsub(/_the_pattern_/, '') # => "ipsum dolor"
¿Fue útil?

Solución

Replace your word with _the_pattern_. Here .* means any character.

s.gsub(/.*(_the_pattern_).*/, '\1')

Make sure the word doesn't contain any special regex characters like ( [ + * etc.

s.gsub(/.*(ipsum dolor).*/, '\1')

\1 is the captured group in () from regex matching.

Otros consejos

"Lorem ipsum dolor sit amet"[/_the_pattern_/]

I would use String#scan followed by Array#join rather than String#gsub, because it is awkward to use the latter for your purpose when the pattern matches more than once. (Since you used gsub rather than sub, I assume multiple occurrences of the pattern is a possibility.)

s = "Lorem ipsum dolor sit amet"          #=> "Lorem ipsum dolor sit amet" 
pattern = %r[ipsum dolor]                 #=> /ipsum dolor/ 
s.scan(pattern).join                      #=> "ipsum dolor" 

s = "A rose by any other name is a rose." #=> "A rose by any other name is a rose." 
pattern = %r[[Aa]\srose]                  #=> /[Aa]\srose/ 
s.scan(pattern).join                      #=> => "A rosea rose"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top