Home > OS >  Conditional(?) regex for numbers
Conditional(?) regex for numbers

Time:11-30

i was trying to create a regex that could match numbers within brackets or not, for example:

(1.000.000,00) //match
(1.000,00)     //match
(100,00)       //match
(10)           //match
(1)            //match

(2.000.000,00  //dont't match
(2.000,00      //dont't match
(200,00        //dont't match
(20            //dont't match
(2             //dont't match

3.000.000,00)  //dont't match
3.000,00)      //dont't match
300,00)        //dont't match
30)            //dont't match
3)             //dont't match

4.000.000,00   //should match
4.000,00       //should match
400,00         //should match
40             //should match
4              //should match

I need to match only numbers(in brackets or not), but only if they have all brackets (2) or none(0)

At the moment this is what i came up with: \((\d [\.,]?) \d*\), it matches the --match and doesn't match the --don't match but should match also the --should match

I've added the javascript tag because i'm using this regex in js and not all of the regex tokens work in the js regex constructor

I'm posting also a regex101 link

CodePudding user response:

If supported, you can usea negative lookbehind to match either with or without parenthesis:

\(\d (?:[.,]\d )*\)|(?<!\S)\d (?:[.,]\d )*(?!\S)
  • \( Match (
  • \d (?:[.,]\d )* Match 1 digits and optionally repeat matching . or , and again 1 digits
  • \) Match )
  • | Or
  • (?<!\S) Negative lookbehind, assert a word boundary to the left
  • \d (?:[.,]\d )* Match 1 digits and optionally repeat matching . or , and again 1 digits
  • (?!\S) Negative lookahead, assert a whitespace boundary to the right

Regex demo

CodePudding user response:

It's usually easier to do regex in multiple passes, but here goes:

/(\((\d [\.,]?) \d*\))|(\d [\.,]?\d*)/gm

You can test it on https://regex101.com/. Usually it's better to process something in multiple passes as you can see the regex becomes even more unreadable. I took your regex and just split it into two regexes: one that requires the parentheses and one that doesn't, then combined them with the or operator. Note that this regex will allow things like "123.3,5.7" as one number, and the capturing groups will be nasty.

  • Related