Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression to get numbers without parentheses ()

I'm trying to create a regex that will select the numbers/numbers with commas(if easier, can trim commas later) that do not have a parentheses after and not the numbers inside the parentheses should not be selected either.

Used with the JavaScript's String.match method

Example strings

9(296,178),5,3(123),10
10,9(296,178),2,5,3(123),3(124,125)
10,7,5(296,293,444,1255),3(218),2,4

What i have so far:

/((^\d+[^\(])|(,\d+,)|(,*\d+$))/gm

I tried this in regex101 and underlined the numbers i would like to match and x on the one that should not.

I tried this in regex101 and underlined the numbers i would like to match and x on the one that should not

like image 972
TestingStuff Avatar asked Jan 23 '26 23:01

TestingStuff


1 Answers

You could start with a substitution to remove all the unwanted parts:

/\d*\(.*?\),?//gm

Demo

This leaves you with

5,10
10,2,5,
10,7,2,4

which makes the matching pretty straight forward:

/(\d+)/gm

If you want it as a single match expression you could use a negative lookbehind:

/(?<!\([\d,]*)(\d+)(?:,|$)/gm

Demo - and here's the same matching expression as a runnable javascript (skeleton code borrowed from Wiktor's answer):

const text = `9(296,178),5,3(123),10
10,9(296,178),2,5,3(123),3(124,125)
10,7,5(296,293,444,1255),3(218),2,4`;
const matches = Array.from(text.matchAll(/(?<!\([\d,]*)(\d+)(?:,|$)/gm), x=>x[1])
console.log(matches);
like image 87
Ted Lyngmo Avatar answered Jan 26 '26 14:01

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!