Bala
Bala

Reputation: 11244

Positive / Negative and Look Ahead / Look Behind confusion?

s = "some {text|in|braces} found"

To get the contents between braces

s.scan(/(?<={).*(?=})/) #=> ["text|in|braces"]

Now to get the contents that are not in braces, I tried

s.scan(/(?<!{).*(?!})/) #=> ["some {text|in|braces} found", ""]

Clearly I am missing something very important.

Upvotes: 3

Views: 121

Answers (2)

fabio
fabio

Reputation: 119

Don't forget to escape special chars with \ ")(?{}".

You can solve this with 2 operations first of all you can islotale your parameter with this regex:

s  = s.gsub(/.*(\{.*\})  # => "text|in|braces"
s.scan(/\w+/) # => ["text", "in", "braces"]

or

s.gsub(/.*(\{.*\}).scan(/\w+/)  # => ["text", "in", "braces"]

Upvotes: 0

Frank Schmitt
Frank Schmitt

Reputation: 30775

Your second regular expression is looking for

  • an arbitrary string ".*"
  • that is not preceded by "{"
  • that is not followed by "}"

which of course matches the whole string, since "some {text|in|braces} found" is neither preceded by a "{" nor followed by a "}".

Upvotes: 2

Related Questions