I'm trying to create a regex that will match all lines with certain PREFIX and the match should end when a char ' is found.
However, if there is a ? before the ', then it should not count it as the end of the line.
Basically the question mark ? serves as a escape char.
This is what I have been using, but it does not work for what i'm trying to do:
This is the regex /SOME_PREFIX+[^']+/
[EDIT] This is the full expected text:
you could have something before'SOME_PREFIX foo bar'something in the middle'SOME_PREFIX BAR FOO ?'SHOULD ALSO MATCH'test'
SOME_PREFIX foo bar' <---Should be a match 1
SOME_PREFIX BAR FOO ?'SHOULD ALSO MATCH' <--- Should be a match 2, but this line does not work, since it only matches up until ?' which is the first ocurrence of the '
For reference: https://regexr.com/63io9
You could use, for example:
const text = "you could have something before'SOME_PREFIX foo bar'something in the middle'SOME_PREFIX BAR FOO ?'SHOULD ALSO MATCH'test'";
const matches = text.match(/SOME_PREFIX(?:[^'?]+|\?'?)*'/g);
console.log(matches);
[^'?]+ matches any character that is not a ' or ?, one or more times, and \?'? means match a ? optionally follwed by a '.
An alternation construct such as (?:x|y) means try and match x first and if it doesn't match, then try and match y.
If a lookbehind is supported in your environment, you could match SOME_PREFIX, and then match any char except SOME_PREFIX or a ' and only match the ' when it it directly preceded by ?
SOME_PREFIX(?:(?!SOME_PREFIX|').)*(?:(?<=\?)'(?:(?!SOME_PREFIX|').)*)*'
Explanation
SOME_PREFIX Match literally(?: Non capture group to repeat as a whole
(?!SOME_PREFIX|') Negative lookahead to assert not SOME_PREFIX or ' directly to the right. Match any char except a newline to not cross lines)* Close the non capture group and optionally repeat it(?: Non capture group to repeat as a whole
(?<=\?)' Match ' only when directly preceded by ?(?:(?!SOME_PREFIX|').)* The same repeating pattern as in the first part)* Close the non capture group and optionally repeat it' Match a single quoteconst regex = /SOME_PREFIX(?:(?!SOME_PREFIX|').)*(?:(?<=\?)'(?:(?!SOME_PREFIX|').)*)*'/g;
const str = "you could have something before'SOME_PREFIX foo bar'something in the middle'SOME_PREFIX BAR FOO ?'SHOULD ALSO MATCH'test'";
console.log(str.match(regex));