MikeC8
MikeC8

Reputation: 3913

Why does free-spacing mode stop negative lookbehind from working?

Consider the following Ruby code:

/(?<!big )dog/.match('I have a big dog.')        # => nil

Now, I'm going to enable free-spacing mode:

/(?x)(?<!big )dog/.match('I have a big dog.')        # => #<MatchData "dog">

Why does this happen, and how can I enable free-spacing mode without breaking my negative lookbehinds?

Upvotes: 4

Views: 51

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

/(?x)(?<!big )dog/.match('I have a big dog.')
#           ^

Note that you have a whitespace after big. Since it's the extended mode, the whitespace is ignored.

You have some options:

  • Use a pattern such as \s or \p{Space}.
  • Use escaped whitespace such as \, i.e. a space preceded by a backslash.
  • Use a character class such as [ ].

For example:

/(?x)(?<!big\s)dog/.match('I have a big dog.')
# => nil

Upvotes: 3

Related Questions