You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写动态正则表达式匹配每个单词中指定字符的首次出现

Solution: Dynamic Regex to Match First Occurrence of a Character in Each Word

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):

  1. (n): This captures your target character—this is the only part you need to change for different characters.
  2. (?<!...): A negative lookbehind that checks what’s immediately before the captured character.
  3. \b: Makes sure we’re looking within a single word (so we don’t accidentally check characters from previous words).
  4. (?:(?!\1).)*: Matches any number of characters that aren’t your target (since \1 refers back to the captured character in step 1).
  5. \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 n in fuunnynsdfdn (the 4th character)
    • The first n in dfdfomdfdnd (the 10th character)
    • The first n in dfdfnntr (the 5th character)
    • The first n in ndfdf (the 1st character)
    • The first n in thatnfdfdfdfd (the 5th character)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:29:45