Search code examples
regexnotepad++

Regex on second occurrence only


Is it possible to perform my Regex on the second occurrence of a specific symbol only?

Regex being used:

@.*

Example data:

Stack@overflow:Stack@overflow

Desired output:

Stack@overflow:Stack

As you can see in the output, everything including and after the second occurrence of an @ has been removed, but the text before it stays.

I'm using Notepad++ or any text editor which allows Regex's to be used.


Solution

  • The pattern @.* will match the first occurrence of @ and will then match any char except a newline until the end of the string and the dot will also match all following @ signs.

    If if : should also be a boundary, you could use a negated character class to match any char except @ or :

    [^@:]+@[^@:]+:[^@:]+
    
    • [^@:]+ Match any char except @ or :
    • @ Match literally
    • [^@:]+ Match any char except @ or :
    • : Match literally
    • [^@:]+ Match any char except @ or :

    Regex demo