1

I am using regex in json. I am trying to get email that doesnt have “abc” on it.

^((?!abc).)*$ but only after @ on the email.

If email is abc@gmail.com it shouldnt match and if email is james@abc.com it should match.

How do i write a regex to say match if email doesnt contain “abc” after @

The fourth bird
  • 154,723
  • 16
  • 55
  • 70

3 Answers3

1

You were very nearly there.

^.*@((?!abc).)*$

should do the trick

sapph
  • 75
  • 10
0

It depends on the flavor of regexp being used by the downstream application. Each language tends to have a slightly different variation, but you can try some of these "tricks".

  • Use the + after an expression to indicate it must appear at least once.
  • For example, [^\@]+ means a non-at-sign character must appear at least once preceding the at-sign.
  • You can replace [^\@]+ with (?:\w|\.|\_|\-)+ to prevent entry of invalid names preceding "@" (for example, you cannot have a percent-sign in an email username)
  • Use (?![Aa][Bb][Cc]) instead of (?!abc) so that the "abc" portion is not case sensitive.
  • If "abc" doesn't need to be right after the "@" then add a non-capturing group representing characters which may appear before "abc" (see the fourth example below)
# lowercase "abc" which must be right after the "@"
"^[^\@]+\@(?!abc)(?:\w|\_|\-|\.)+(?:[.]\w{2,4})+$"

# case insensitive "abc" which must be right after the "@" (which may be preceded by any non-"@" characters)
"^[^\@]+\@(?![Aa][Bb][Cc])(?:\w|\_|\-|\.)+(?:[.]\w{2,4})+$"

# case insensitive "abc" which must be right after the "@" (which may be preceded by valid characters, such as alphabet letters, period, underscore)
"^(?:\w|\.|\_|\-)+\@(?![Aa][Bb][Cc])(?:\w|\_|\-|\.)*(?:[.]\w{2,4})+$"

# case insensitive "abc" which may be preceded by other valid characters
"^(?:\w|\.|\_|\-)+\@(?!(?:\w|\_|\-|\.)*[Aa][Bb][Cc])(?:\w|\_|\-|\.)*(?:[.]\w{2,4})+$"
ELinda
  • 2,658
  • 1
  • 10
  • 9
0

You can use

^[^@]*@(?!.*abc).*

See the regex demo.

If there can't be abc immediately after @, you need to remove .* before abc in the pattern and use

^[^@]*@(?!abc).*

See this regex demo.

The regex matches any zero or more chars other than @, a @, then makes sure there is no abc after any zero or more chars other than line break chars as many as possible immediately to the right of @, and then matches the rest of the string.

Note you need to use an inline modifier (?i) to match the abc in a case insensitive way, or use a [aA][bB][cC] workaround if the inline flags are not supported:

(?i)^[^@]*@(?!.*abc).*
^[^@]*@(?!.*[aA][bB][cC]).*
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563