Invalid lookbehind pattern

Viewed 53

I am simply trying to take the following text:

Password length (length ordered)
5 = 1 (0.37%)   
6 = 1 (0.37%) 
7 = 1 (0.37%)         
8 = 157 (58.58%) 
9 = 55 (20.52%)
10 = 33 (12.31%)
11 = 12 (4.48%)                  
12 = 6 (2.24%)                   
13 = 2 (0.75%)  

And find every new line that exists between Password Length and \n\n. Here's what I was currently doing

data[/(?<=Password length)(.*?)(?=\n\n)/m]

but that captures (length ordered) in the first line.

I have tried to do something like this:

44] pry(main)> data[/(?<=Password length.*?\n)(.*?)(?=\n\n)/m]
(eval):2: invalid pattern in look-behind: /(?<=Password length.*?\n)(.*?)(?=\n\n)/m

To basically capture everything after Password length up to the new line, but as you can see above I get an error about the invalid pattern in look-behind.

What should I be doing instead of this to fix this?

1 Answers

You can use

data[/Password length.*\R(?m:(.*?))\R{2}/, 1]

See the Rubular demo. Details:

  • Password length - a literal string
  • .* - the rest of the line
  • \R - a line break sequence
  • (?m:(.*?)) - An inline modifier group where . matches any char including line break chars, capturing group 1 matching any zero or more chars but as few as possible
  • \R{2} - double line break sequence.

The 1 argument returns the value inside the first capturing group only (see the str[regexp, capture] → new_str or nil reference).

An alternative:

data[/Password length.*\R\K.*(?:\R(?!\R).*)*/]

See this Rubular demo. Details:

  • Password length.*\R - Password length, the rest of the line and a line break sequence
  • \K - match reset operator, it removes all text matched so far from the match memory buffer
  • .* - a line, any zero or more chars other than line break chars as many as possible
  • (?:\R(?!\R).*)* - zero or more lines that do not end with double line break sequence where \R(?!\R).* matches a line break not immediately followed with another line break sequence, and .* matches the rest of the line.
Related