Home > Mobile >  regex to select text before term
regex to select text before term

Time:10-18

I have some strings that have the same pattern:

"abc 1x de" "abc 2x rf" "abc 3x gh"

I need to select "x" and the number before "x". How can I do that? Thanks.

CodePudding user response:

["abc 1x de","abc 2x rf","abc 3x gh","4x ABC" "ABC 5x"].map { |s| s[/(?>\dx)/] }
=> ["1x", "2x", "3x", "4x"]

CodePudding user response:

Just check for the \b word boundary using String#scan. Using Ruby 3.0.2:

["abc 1x de", "abc 2x rf", "abc 3x gh", "4x ABC", "ABC 5x"].
 flat_map { _1.scan /\b(?:\d x)\b/ }
#=> ["1x", "2x", "3x", "4x", "5x"]

As long as x doesn't appear in your other strings, this will work regardless of how many digits you have, or where the substring appears in your string.

  •  Tags:  
  • ruby
  • Related