Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex matching algorithm on count occurrences

I spent ours on getting the solution for my little regex problem.

Assuming I have a string containing german umlauts. e.g. "Brötchenkörbe".

I need the best regex condition to match ALL 'ö' except the last one, if the occurrence of 'ö' is > 1

(else) If there is only ONE 'ö' in the string, I want to match that character as well.

So that I would get the following results:

Brötchenkörbe

Möhrenlösungslöcher

Löschwagen

I found an expression that does match every 'ö', except the last one. But the is no match, if the 'ö' occures only one time:

/(ö(?=[^.]*[ö]))/

does anyone get the trick?

I need that expression to work on a filter on my solr server.

Background: I use a stemm-Filter to stemm words in german. but the used filter "SnowballPorterFilter" does change every umlaut (öäüÖÄÜ) to (oauOAU).

Only the last umlaut need to be changed from that filter, so that I want to use a regex-filter ("PatternReplaceFilterFactory") which protects all other umlauts from that change, and reverse that protection after running that stemm-filter.

e.g.: Möhrenlösungslöcher gets "M#o#hrenl#o#sungslöcher" , filter does "M#o#hrenl#o#sungsloch" , and then reverse protection to "Möhrenlösungsloch"

like image 467
the_casper Avatar asked Jul 04 '26 13:07

the_casper


1 Answers

Qeole got the solution:

In three steps:

  1. Place umlauts to fix between # signs with following regex:

    /(^([^äöü]*))(ä|ö|ü)|(ä|ö|ü)(?![^äöü]*$)/gm
    

    (replace with $1#$3$4#)
    All umlauts to fix are now between # signs. So let's keep going…

  2. Change all #ä# to #a#.

  3. Repeat for #ö# and #ü#.

like image 82
the_casper Avatar answered Jul 07 '26 03:07

the_casper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!