简体   繁体   中英

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

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?

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

You can just use the following to match:

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

And replace with $1$2

See DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM