Search code examples
regexregex-groupregexp-replace

RegEx find all matches not present in the following set


How to perform a regex replace on the dot symbol that is not present within a specific match (for example in an image HTML tag)

str = "Hi. the symbol before me is my match target <img src='http://skip.these.dots/and.this.as.well' alt='me.three' /> but still match this."

To be replaced with (for example) * symbol

res = "Hi* the symbol before me is my match target <img src='http://skip.these.dots/and.this.as.well' alt='me.three' /> but still match this*"

Solution

  • Try this:

    \.(?![^<]*\/>)
    

    Demo

    The regex engine performs the following operations.

    \.      # match period
    (?!     # begin negative lookahead
      [^<]* # match 0+ chars other than '<'
      \/>   # match '/>'
    )
    

    The negative lookahead fails if it encounters /> after the period without any intervening <, meaning the period must be between a < and an />.

    You wish to replace each match of a period with *. How you do that depends on the language you are using, but it is undoubtedly straightforward.