Home > Blockchain >  Regex for containing x AND not containing y without lookarounds
Regex for containing x AND not containing y without lookarounds

Time:07-21

I'm trying to write a simple regex for a string that contains a dot (.) AND doesn't contain @.

I managed to do this like this:

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

and it works! But I'm getting an error:

'Value "/(^(?!.*@).*\..*$)" must be a valid regular expression. Details: invalid or unsupported Perl syntax.'

I've searched and found out that the issue is with the negation part - "?!". Trying to change the expression to work with ^ but with no luck.

Would appriciate your help, thanks.

CodePudding user response:

You can use a regex that does not rely on lookarounds:

^[^@.]*\.[^@]*$

Or, if you have trouble with finding the right amount of escaping backslashes:

^[^@.]*[.][^@]*$

Details:

  • ^ - start of string
  • [^@.]* - zero or more chars other than a . and @
  • \. / [.] - a mere dot char
  • [^@]* - zero or more chars other than a @ char
  • $ - end of string.
  • Related