如何用R语言gsub()仅在无前导元音时替换ae/oe/ue为变音符号?
Got it, let's fix this umlaut conversion issue! The problem with your current function is that it replaces every occurrence of "ae", "oe", "ue" no matter what comes before them—like in "Neue", the "ue" follows a vowel "e" so it shouldn't be converted.
Here's how to adjust it using negative lookbehind assertions in regex, which let us check that the target character pair isn't preceded by a vowel. R supports these with Perl-compatible regex, so we'll add perl=TRUE to each gsub call:
umlaut_conversion <- function(text){ text <- text %>% gsub('(?<![aeiouAEIOU])ae', 'ä', ., perl = TRUE) %>% gsub('(?<![aeiouAEIOU])oe', 'ö', ., perl = TRUE) %>% gsub('(?<![aeiouAEIOU])ue', 'ü', ., perl = TRUE) return(text) }
Let's test it with your example:
umlaut_conversion('Neue Woerter!') # Output: "Neue Wörter!"
Breakdown of the solution:
(?<![aeiouAEIOU]): This is the negative lookbehind assertion. It checks that immediately before the following character pair ("ae", "oe", or "ue"), there is not any vowel (lowercase or uppercase).- We use
perl=TRUEbecause R's base regex engine doesn't support lookbehind assertions—Perl-compatible mode enables this functionality. - The order of replacements doesn't matter here since we're targeting distinct, non-overlapping character pairs.
This way, only instances like "Woerter" (where "oe" comes after consonant "W") get converted, while "Neue" (where "ue" comes after vowel "e") stays exactly as intended.
内容的提问来源于stack exchange,提问作者Marvin

