-2

I want to get the result from these 3 string values 'one two three' which may all be present in the text. I want to use regex to search for 'one' and return it (if found); otherwise search for 'two' and return it (if found); finally if 'two' was not found simply match with 'three'.

montrealist
  • 5,593
  • 12
  • 46
  • 68
RKRaider
  • 17
  • 5
  • 3
    This sounds like you need some control flow in addition to regex (if re is indeed the right solution. What language are you using? what have you tried? – 1252748 Sep 26 '18 at 19:40
  • Please, take your time and train yourself how to make a readable and informative question like [this](https://stackoverflow.com/questions/51846536/islands-and-gaps-issue). – JohnyL Sep 26 '18 at 19:52
  • @1252748: no, a simple alternation is already a control flow. (In the same way you can mimic an *if then else* only with the `||` (OR operator) in C language or Javascript). ex: `(a=5*3)==14 || (a=4*3)==12;` => `a` value is 12. – Casimir et Hippolyte Sep 26 '18 at 20:45
  • Given the string "three two one", what result do you wish to see? – glenn jackman Sep 26 '18 at 21:15

3 Answers3

0

If I understand well your question:

^(?:.*\K\bone\b|.*\K\btwo\b|.*\K\bthree\b)

Each branch tests one word, since an alternation is evaluated from left to right, the first correct assertion wins, and this independently of the words order in the string.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

RkRaider Here I am using If-Else conditional regex with nested condition.

If-Else in Regex :

(?(?=regex)then|else)

Regex :

(?(?=one)one|(?(?=two)two|three))

Verfiy through regex101 :

enter image description here

Usman
  • 1,983
  • 15
  • 28
0

I suspect you want

(?=.*\b(one)\b)?(?=.*\b(two)\b)?(?=.*\b(three)\b)?

But then you need a bit of logic in your programming language to determine which one you found with the highest priority. Example

$ cat strings
one two three
two one three
three two one
bone two threed
bone town three

$ perl -lnE '
    print; 
    /(?=.*\b(one)\b)?(?=.*\b(two)\b)?(?=.*\b(three)\b)?/ and print "got:", $1 || $2 || $3
' strings
one two three
got:one
two one three
got:one
three two one
got:one
bone two threed
got:two
bone town three
got:three
glenn jackman
  • 238,783
  • 38
  • 220
  • 352