Search code examples
rubyregex-greedynon-greedy

ruby regex to find nested matches


My regex is

/a .*programming .*test .*this/i

and test string is

This is a test This is a programming test This is a programming test in any language

The match I'm getting is

a test This is a programming test This

But there is another shorter match "a programming test This" , which this regex is unable to find , i used scan method to find all the matches but that even can not capture this .

Any help is greatly appreciated


Solution

  • RegexP is a very complex thing! You really need to know which parts of your string are critical to match and which arent. There are tons of ways to accomplish a match, but it's not easy to guess what you ACTUALLY want:

    s = "This is a test This is a programming test This is a programming test in any language"
    s.match(/a [^a]*programming .*test .*this/i)[0]
     => "a programming test This"