Search code examples
rubyregexlookbehind

How to match a word that is not preceded by "=" using Regex?


I would like to extract symbols from Fortran codes in Ruby. The symbols would have the following patterns (NOTE: the variable type and attribute parts have been filtered out):

a = b, c(2)       ! Match result should be "a" and "c"
d(3) = [1,2, &    ! Match result should be "d"
  3]

The Regex that I have tried is ((?<!=)\w+(?![^\[]*\]+)(?=( |,|\(|$))) with lookaround stuffs. But due to the restriction of lookbehind, I can not match "= *" to exclude b.

I used Rubular for testing. For your convenience, see here.

Thanks in advance!


Solution

  • In order to make your regex work you can first replace all trailing whitespace after =

    .gsub(/=\s+/, '=').scan(/((?<!=)\w+(?![^\[]*\]+)(?=( |,|\(|$)))/)