Search code examples
regexsalesforceregex-group

RegEx: Excluding a pattern from the match


I know some basics of the RegEx but not a pro in it. And I am learning it. Currently, I am using the following very very simple regex to match any digit in the given sentence.

/d

Now, I want that, all the digits except some patterns like e074663 OR e123444 OR e7736 should be excluded from the match. So for the following input,

Edit 398e997979 the Expression 9798729889 & T900980980098ext to see e081815 matches. Roll over matches or e081815 the expression e081815 for details.e081815 PCRE & JavaScript flavors of RegEx are e081815 supported. Validate your expression with Tests mode e081815.

Only bold digits should be matched and not any e081815. I tried the following without the success.

(^[e\d])(\d)

Also, going forward, some more patterns needs to be added for exclusion. For e.g. cg636553 OR cg(any digits). Any help in this regards will be much appreciated. Thanks!


Solution

  • Try this:

    (?<!\be)(?<!\d)\d+
    

    Test it live on regex101.com.

    Explanation:

    (?<!\be) # make sure we're not right after a word boundary and "e"
    (?<!\d)  # make sure we're not right after a digit
    \d+      # match one or more digits
    

    If you want to match individual digits, you can achieve that using the \G anchor that matches at the position after a successful match:

    (?:(?<!\be)(?<=\D)|\G)\d
    

    Test it here