Home > Software design >  regular expression affected by everything around it preventing a match
regular expression affected by everything around it preventing a match

Time:02-04

I have a simple regular expression for emails that I want to use, so it matches [email protected] for example, I don't care about what's around the email, except for one case when it starts with a * I don't want the email to match in that case only. The regex I have does this but prevents other matches, for example, test>[email protected] it should match [email protected] in this case, but it doesn't, I've done extensive research I can't seem to figure it out, it should ONLY NOT match if there is a * in front of the email, no other case, from what I understand my current regex should do that.

((^[^\*][a-zA-Z0-9_. -] @[a-zA-Z0-9-] \.[a-zA-Z.] \D)$)

should match what is bolded

shouldn't match

CodePudding user response:

What you could do is to make sure the character before the email is not a * using negative lookbehinds:

(?<!\*)\b[a-zA-Z0-9_. -] @[a-zA-Z0-9-] (?:\.[a-zA-Z] ) 

Here are the test cases


For more restricted tests you may also try (?<![*. -])\b(?![. -])[a-zA-Z0-9_. -] @[a-zA-Z0-9-] (?:\.[a-zA-Z] ) which excludes

*[email protected]
*[email protected]
*abc [email protected]

etc.

  •  Tags:  
  • Related