如何编写动态正则表达式匹配每个单词中指定字符的首次出现
Got it! To match the first occurrence of any specified character in each word (with just one quick modification, exactly like your existing last-occurrence regex), here's the pattern you need:
(X)(?<!\b(?:(?!\1).)*\1)
How It Works
Let’s use n as an example (just swap out X for whatever character you want to target):
(n): This captures your target character—this is the only part you need to change for different characters.(?<!...): A negative lookbehind that checks what’s immediately before the captured character.\b: Makes sure we’re looking within a single word (so we don’t accidentally check characters from previous words).(?:(?!\1).)*: Matches any number of characters that aren’t your target (since\1refers back to the captured character in step 1).\1: The target character itself.
All together, the lookbehind ensures that before the current character, there are no other instances of that character in the same word. That means we only pick up the very first occurrence in each word.
Testing with Your Sample String
Using your input: "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
- If you set
X = n, the regex will match:- The first
ninfuunnynsdfdn(the 4th character) - The first
nindfdfomdfdnd(the 10th character) - The first
nindfdfnntr(the 5th character) - The first
ninndfdf(the 1st character) - The first
ninthatnfdfdfdfd(the 5th character)
- The first
How It Lines Up with Your Original Regex
Your existing regex for last occurrence uses a negative lookahead to ensure no more of the character comes after. This one uses a negative lookbehind with a backreference to ensure no instances came before—keeping that same "one modification only" convenience you wanted.
内容的提问来源于stack exchange,提问作者Andre Elrico

