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")
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.
CodePudding user response:
Obviously going for regex
is a good option. But there's a way to achieve this with substring
and indexOf
too.
var str = "location = \"Somewhere\" and (Person IN (4,1,8,2,10,24,32,15,7)) and status in (\"Closed\")"
let index1 = str.indexOf("(Person IN");
let index2 = str.substring(index1).indexOf(")");
console.log(str.substring(index1, index1 index2 2))
CodePudding user response:
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))
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));