Search code examples
regexpcreregex-lookarounds

Regex: don't match if the pattern start with /


My regex (PCRE):

\b([\w-.]*error)\b(?:[^-\/.]|\.\W|\.$|$)

is a match (the actual match is surrounded by stars) :

**this.is.an.error**  
**this.IsAnerror**  
**this.is.an.error**.  
**this.is.an.error**(  
bla **this_is-an-error**  
**this.is.an.error**:  
this is an (**error**)  

not a match:

this.is.an.error.but.dont.match  
this.is.an.error-but.dont.match  
this.is.an.error/but.dont.match  
this.is.an.error/  
/this.is.an.error 

for this sample: /this.is.an.error I can't manage to have a condition that will reject the whole match if it starts with the character /. every combination I've tried resulted in some partial catch (which is not the desired).

Is there any simple or fancy way to do that?


Solution

  • You can try to add lookabehinds at the beginning instead of a word boundary:

    (?<!\/)(?<=[^\w-.])([\w-.]*error)\b(?:[^-\/.]|\.\W|\.$|$)
    

    Explanation:

    • (?<!\/) - negative lookbehind assuring there is no / before the first character;
    • (?<=[^\w-.]) - word boundary implementation taking into account your extended definition of characters accepted for a word [\w-.];

    Demo