Reputation: 79
I am trying to check patterns in a string using regex. My requirements are
%
or (%
there should be a number and vice versa any number should be preceded by %
always%
(
)
and
or
numeric valueValid string (%1 and %2 or %3)
Invalid %%1
I tried the following
regex ^[%(]+[%0-9]+[(]
Please help
Upvotes: 2
Views: 254
Reputation: 1069
This should do it:
^(?:\(|%[0-9]+)(?:\s+|%[0-9]+|and|or|\(|\))*$
Starts with an opening bracket or a percent then a series of numbers, then goes on to allow spaces or a percent followed by a series of numbers any number of times. If you give a more specific example of what you are trying to match I can be more specific
This does not force matching brackets. You need a recursive js function for that
EDIT
Alright, here is a more specific function to account for spacing and numbers around seperators
^(?:\(|%[0-9])(?:\sand\s|\sor\s|\(+)(?:(?:%[0-9]|\)+)(?:\s(?:and|or)\s(?:%[0-9]|(?:\(\s?)+))?)*\s?\)*$
This will match something like this: %3 and %4 or ( %2 or %3 ) but fails when you try it on: %3 and %4or ( %2 or %3 ) note the missing space between the %4 and the or
Again, brackets dont need to be closed so it matches: %3 and %4 or ( %2 or %3 and it also matches: %3 and %4 or ( %2 or %3 ))))
it can deal with immediately nested brackets like this: %3 and %4 or ((%2 or %3) and %9 )
Im sure I have missed cases, let me know what issues your run into
Upvotes: 3
Reputation: 1363
Here's a solution :
^(%\d|\()(%\d|and|or|[\s()])*$
This will match strings beginning with "%N", followed by any combination of "and", "or", whitespaces, ( ), and % followed by a number.
Upvotes: 0
Reputation: 4956
I would remove the white space from the string first just to make the regex easier.
This doesn't match exactly what you described, but matches what I think you're trying to do based on your example:
\(?%\d+\)?((and|or)\(?%\d+\)?)*
Note that it does not guarantee that the parentheses are all matched.
Upvotes: 0