I am trying to check patterns in a string using regex.My requirements are
- The string should always start with
%or ( - Immediately After
%there should be a number and vice versa any number should be preceded by%always - the string can only contain following characters and word
%()andornumeric value
Valid string (%1 and %2 or %3)
Invalid %%1
I tried the following
regex ^[%(]+[%0-9]+[(]Please help
- 1Looks like whitespace characters are OK too, right?Pointy– Pointy2013-12-05 14:52:16 +00:00CommentedDec 5, 2013 at 14:52
- Yes whitespace characters are okJSLearner– JSLearner2013-12-05 14:53:29 +00:00CommentedDec 5, 2013 at 14:53
- Try regex ^[%(]+[%0-9\s]+[)]Parkash Kumar– Parkash Kumar2013-12-05 14:55:12 +00:00CommentedDec 5, 2013 at 14:55
4 Answers4
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 %3and 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
7 Comments
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.
Comments
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.
3 Comments
Comments
Explore related questions
See similar questions with these tags.
