Frage

Let's say I have the string:

we have apple, coconut and grapes.

If I use the regex:

^.*\b((apple)|(coconut)|(grape)|(grapes)).*$

to replace with

|$2|$3|$4|$5

It will output |||grape| as it goes greedy by .* and then matches from right to left.

How can I prioritise the replace to first try out the first pattern group (in my example '(apple)') for the whole string before trying group 2 or 3 and so on, sort of like it happens for just one character match when I replace order between grapes and grape changing the output to |||grapes|.

I can do this using multiple replaces but I fear the overhead of calling regex from mssql multiple times might result in too much overhead.

War es hilfreich?

Lösung

Try something like this maybe?

^((?:.*?(\bapple\b))|(?:.*?(\bcoconut\b))|(?:.*?(\bgrape\b))|(?:.*?(\bgrapes\b))).*$

apple has priority, then coconut, afterwards grape, and last grapes.

Andere Tipps

Alternatives in a regex alternation are tried from left to right, so you either need to put the longer alternatives first

^.*\b((apple)|(coconut)|(grapes)|(grape)).*$

or make sure that only entire word matches by using another word boundary:

^.*\b((apple)|(coconut)|(grape)|(grapes))\b.*$
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top