marcamillion marcamillion - 24 days ago 5x
Ruby Question

How do I extract this substring within this string?

I have the following text:

"Showing1-30\nof 1404results"

What I want to pull out is the

How do I do that?

I was thinking I would use a regexp to match just the string between the words
, but can't quite figure out how to do that.

Or is there another way, say a built-in Ruby method I could use that is efficient?

I was also considering using
, but the spacing is off so it looks like this:

=> ["Showing1-30", "of", "1404results"]

How do I do what I want?


Match "of" followed by one or more spaces, followed by one or more digits in capture group 1, followed by "results", then retrieve the contents of capture group 1.

"Showing1-30\nof 1404results"[/of\s+(\d+)results/,1]
  #=> "1404"


Match the string that is preceded by "of" followed by one1 space (positive lookbehind) and is followed by "results" (positive lookahead)

"Showing1-30\nof 1404results"[/(?<=of\s)\d+(?=results)/]
  #=> "1404"


Match "of" followed by one or more spaces, forget everything matched so far (\K), match one or more digits followed by "results" (positive lookahead)

"Showing1-30\nof 1404results"[/of\s+\K\d+(?=results)/]
  #=> "1404"

It may be desirable to change the first regex to


in case someone decides to "correct" the string to read "Showing 1-30\nof 1404 results"[/(?<=of\s)\d+(?=results)/].

1 Ruby's positive lookbehinds cannot be variable length; hence, \s+ is not permitted here.