Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return specific portion of a string in specific format that includes a number[]

I won’t lie, regex is definitely not a strength of mine so hoping to borrow the talent of someone whose it is.

What I need to do is from a string that would look something like this;

location = "Somewhere" and (Person IN (4,1)) and status in ("Closed")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need specifically this portion;

(Person IN (4,1))

Wherein the portion of (4,1) could include a one-to-many array of number. So for example if I receive;

location = "Somewhere" and (Person IN (4,1,8,2,10,24,32,15,7)) and status in ("Closed")

Then the portion I need to extract would be;

(Person IN (4,1,8,2,10,24,32,15,7)) and the words contained are not case sensitive (eg; Person=person, IN=in) and there may be spaces between the numbers in the number[], but both the string and the number[] will be contained in (...) as shown and there may be other random stuff before and after the string contained.

A horrible attempt might be like: /(?:Person in \()(?:([\/\s"](?:,?)))(?:\))?/gm but I know obviously that’s not what I need, please advise and help a regex amateur lol.

>Solution :

You can match the opening and closing parenthesis and the comma separated digits in between, where there can be optional whitspace chars surrounding the digits.

\(Person in \(\s*\d+\s*(?:,\s*\d+\s*)*\)\)
  • \(Person in \( Match (Person in (
  • \s*\d+\s* Match 1+ digits between optional whitespace chars
  • (?:,\s*\d+\s*)* Optionally repeat matching a comma and 1+ digits between optional whitespace chars
  • \)\) Match ))

Regex demo

An Example in Javascript

const regex = /\(Person in \(\s*\d+\s*(?:,\s*\d+\s*)*\)\)/gi;
const str = `location = "Somewhere" and (Person IN (4,1)) and status in ("Closed")

location = "Somewhere" and (Person IN ( 4, 1,8,2, 10,24 ,32,15, 7 )) and status in ("Closed")

location = "Somewhere" and (Person IN ()) and status in ("Closed")

location = "Somewhere" and (Person IN ( 4 )) and status in ("Closed")

`;
console.log(str.match(regex));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading