Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex matching conditional strings

Tags:

regex

For example, if I have the following strings:

99%89 (should match)
99%? (should match)
?%99 (should match)
?%? (should not match)
?%99%99 (should match)
99%99%99%? (should match)

essentially the first or second element can be a ? or a number, but both elements cannot be ?. I tried thinking of something like:

[0-9]*|[?](?!\?)[%][0-9]*|[?]

But this does not yield the correct answer, any help would be appreciated

like image 454
AdamantiumPrime Avatar asked Jan 25 '23 09:01

AdamantiumPrime


1 Answers

With your shown samples, could you please try following.

^(?:(?:\?(?:(?:%\d+){1,})?)|(?:(?:(?:\d+%){1,})?\?(?:(?:%\d+){1,})?)|(?:\d+%\d+))$

Online demo for above regex

Explanation: Adding detailed explanation for above.

^(?:                       ##Matching from starting of the value, starting a non-capturing group from here.
 (?:\?                     ##Starting non-capturing group(one for understanding purposes) matching literal ? here.
    (?:(?:%\d+){1,})?      ##In a non capturing group looking for % with 1 or more occurrences of digits and matching this group match keeping it optional.
  )|                       ##Closing one non-capturing group here, with OR condition here.
 (?:                       ##Starting non-capturing group(two) here.
    (?:(?:\d+%){1,})?\?    ##Looking for digits with % one or more occurrences in a non-capturing group keeping it optional followed by ?
    (?:(?:%\d+){1,})?      ##Checking for % digits one or more occurrences in a non-capturing group keeping it optional followed by ?
 )|                        ##Closing two non-capturing group here, with OR condition here.
 (?:\d+%\d+)               ##In a non-capturing group looking for 1 or more digits % one or more digits
)$                         ##Closing  1st non-capturing group at the end of value.
like image 65
RavinderSingh13 Avatar answered Feb 04 '23 09:02

RavinderSingh13