How do I replace a comma separated list of strings with the first occurrence?

115 views Asked by At
WHERE MATCH (COALESCE(f1, f2, f3)) AGAINST (?) > 0
WHERE MATCH (COALESCE(f1)) AGAINST (?) > 0

Wanted:

WHERE MATCH (f1) AGAINST (?) > 0
WHERE MATCH (f1) AGAINST (?) > 0

Need to substritute COALESCE(f1, f2, f2, ...) with just f1, that is the first string if multiple string are present (separated by ,) or just the string itself.

I'm working on this:

#\s*match\s*\((\s*coalesce\s*\((.+)\s*\))\s*\)\s+against#/i

And i'm capturing both what's inside MATCH (1, what's need to be replaced) and what's inside COALESCE (2, the replacement).

How do I substituite 1 with the first value inside 2?

2

There are 2 answers

1
Jonny 5 On BEST ANSWER

Replace should start at COALESCE but the previous part must match. Use \K for resetting after (where replacing should start). So the first part could look like MATCH\s*\(\K here starts replacing and pattern continues: \s*COALESCE\s*\(\s*([^,)]+)... capturing in first capture group.

And the optional part (?:,[^)]*)? to meet a closing bracket. For the AGAINST part a lookahead can be used: (?=\)\s*AGAINST). So the whole pattern could be:

/MATCH\s*\(\K\s*COALESCE\s*\(\s*([^,)]+)(?:,[^)]*)?\)(?=\)\s*AGAINST)/i

And replace with captured $1. Test at regex101.com

3
karthik manchala On

You can just use the following to match:

(MATCH\s*\()COALESCE\(([^,)\s]+)(?:\s*,[^)]+)?\)

And replace with $1$2

See DEMO