Regex stop match immediatlly or if there is a comma

Viewed 69

I probably didn't phrase the question in the best way, but bear with me

Having this string

select * from my_functions (in_p1 := remove,
                                   in_p2 := $1,
                                   in_p3 := remove,
                                   in_p4 := $2,
                                   in_p5 := remove,
                                   in_p6 := $3,
                                   in_p7 := remove)

I need to remove the parameters that are matched for retrieval, with the remove keyword

So I built this text = text.replace(/,[^,]*?remove/g, ''), which works for every case except p1. How can I tell it to stop the match immediattly or if there's a comma, to only stop after the comma ?

1 Answers

Since you need to remove the comma in two possible places, the only option I see for doing this with a single regex is an alternation:

//                   vvvvvvvvvvvvv−−−−−−−−−−−−−−−−−−−−−−−−−−−−− first alternative
text = text.replace(/,[^,]*?remove|(?<=\()[^,]*?remove,/g, '');
//                                 ^^^^^^^^^^^^^^^^^^^^−−−−−−−− second alternative

The alternatives are your original expression that matches things other than in_p1, and an alternative that matches in_p1 and removes the comma after it (rather than in front of it).

Example:

let text = `select * from my_functions (in_p1 := remove,
                                   in_p2 := $1,
                                   in_p3 := remove,
                                   in_p4 := $2,
                                   in_p5 := remove,
                                   in_p5_ := remove,
                                   in_p6 := $3,
                                   in_p7 := remove)`;
                                   
text = text.replace(/,[^,]*?remove|(?<=\()[^,]*?remove,/g, '');
console.log(text);

Note that that uses a lookbehind for the (. Lookbehind is relatively new to JavaScript. I think we can get rid of the lookbehind if your target platform doesn't support it by using a capture:

text = text.replace(/,[^,]*?remove|(\()[^,]*?remove,/g, '$1');

Example:

let text = `select * from my_functions (in_p1 := remove,
                                   in_p2 := $1,
                                   in_p3 := remove,
                                   in_p4 := $2,
                                   in_p5 := remove,
                                   in_p5_ := remove,
                                   in_p6 := $3,
                                   in_p7 := remove)`;
                                   
text = text.replace(/,[^,]*?remove|(\()[^,]*?remove,/g, '$1');
console.log(text);


Note that I added an extra parameter in there just to double-check that two "remove" parameters in a row were removed correctly.

Related