JSLearner
JSLearner

Reputation: 79

Checking patterns using regex in Javascript

I am trying to check patterns in a string using regex. My requirements are

  1. The string should always start with % or (
  2. Immediately After % there should be a number and vice versa any number should be preceded by % always
  3. the string can only contain following characters and word % ( ) and or numeric value

Valid string (%1 and %2 or %3)

Invalid %%1

I tried the following

regex ^[%(]+[%0-9]+[(]

Please help

Upvotes: 2

Views: 254

Answers (4)

wolffer-east
wolffer-east

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

enter image description here

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

penjepitkertasku
penjepitkertasku

Reputation: 562

try this, perhaps can help :

^[%][0-9]+|^[(][%][0-9]+[)]

http://RegExr.com?37h10

Upvotes: 0

Theox
Theox

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

Sparafusile
Sparafusile

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

Related Questions