Question

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!

Was it helpful?

Solution

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

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

OTHER TIPS

One easy thing you could do is split the line in two (at the '=') and only do your regex on the left operand.

That way you don't have to write any complex regex.

My advice would be to separate your regex into 2 expressions. Regex needn't always be a one-liner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top