marcamillion marcamillion - 2 months ago 7
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
1404
.

How do I do that?

I was thinking I would use a regexp to match just the string between the words
of
and
results
, 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
split
, but the spacing is off so it looks like this:

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


How do I do what I want?

Answer

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"

or

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"

or

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

/(?<=of\s)\d+\s*(?=results)/

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.

Comments