Ruby regex for 3 expressions (with AND)

1318 views ruby
7

I bit new and very excited about ruby, but stumbled upon this task: I need to return TRUE if string has ALL 3 values to search, so all of them should work with AND. They only syntax I found is with pipe which is not working for my situation, I can use separate match/scan for 3 cases and they if TRUE for all ,but I think should be something easier then than, I might confused with terminology. I've checked groups but looks like it's not for my case. I have a lot of regex options around those keywords so I 100% need regex, for simplicity I didn't write them all. It should work no matter what order for those keywords.

In this code below I need to get TRUE only for first mystring3

mystr3= '  OK 3 values MyServer  and myNode  and myuser  TRUE '
mystr2= 'has on 2 values   mynode##  and .myserver should be FALSE'
mystr1= ' has on 1 values  Myserver  should be FALSE'

regex1 = /\bmyserver\b/i ;   regex2 = /\bmynode\b/i ;   regex3 = /\bmyuser\b/i

regex = /#{regex1}|#{regex2}|#{regex3}/  ## AND  /#{regex2}/  and /#{regex3}/

p  'match3 ' + mystr3.scan(regex).to_s
p  'match2 ' + mystr2.scan(regex).to_s

answered question

1 Answer

12

To check to see that the string matches all three, you can use lookahead for the subexpression three times:

regex = /^(?=.*#{regex1})(?=.*#{regex2})(?=.*#{regex3})/

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories