Home > other >  RegEx - avoid matching a word ending with a specific character
RegEx - avoid matching a word ending with a specific character

Time:11-22

I am trying to create a regex (regexp) that will avoid matching words ending with '@', '-', '!', ':' and '>'

The rules are as follows - the name should begin with @ can have any character after it except the ones above. So in the following strings: 'zhsvfghzfajhuib@Bobbie?skvshvfhj!G!' - @Bobbie? will match '768huehfvwkjv@Lana97958749ndgjhb!G!' - @Lana9 will match ',vbfnhytjnh@Sammie-sjvjhsvfjj!G!kjdbdjb' - @Sammie- will NOT match, because the character after the name is in the above range.

My latest attempt is : @(?[A-Za-z] )[^@-!:>] but all it did was to remove the last character and still matched.

I tried:

  • adding another character in the search @(?[A-Za-z] ).[^@-!:>] but the search just moved to the next character.
  • adding a word boundary @(?[A-Za-z] )\b[^@-!:>] which help in some cases but not all

CodePudding user response:

Consider the following regex for the character c. It will avoid all words that are ending with c:

/\b\w [^c]\b/

Note: Here, \b: Word boundary, \w: Word, [^]: Negated set.

CodePudding user response:

If supported, you can use an atomic group:

@(?>(?<name>[A-Za-z] ))[^@\-!:>]

Regex demo

Another option is using a positive lookahead with a capture group and a backreference as there is no backtracking in lookarounds:

@(?=([A-Za-z] ))\1[^@\-!:>]

Regex demo

  • Related