user15743714
user15743714

Reputation: 29

I want to look for matches only after special character in regex

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 [email protected] it shouldnt match and if email is [email protected] it should match.

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

Upvotes: 1

Views: 65

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626871

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]).*

Upvotes: 0

ELinda
ELinda

Reputation: 2821

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})+$"

Upvotes: 0

sapph
sapph

Reputation: 97

You were very nearly there.

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

should do the trick

Upvotes: 1

Related Questions