Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match exactly 1 anywhere in string

Tags:

regex

So I need to match upper and lower case a-z letters, period (.) and @ in a string. As a complication the string must have @ exactly once anywhere in the string and . at least once anywhere in the string.

abcd@.  // match
@ab.cd  // match
a@cd@.  // no match
abcd@  // no match

I've tried to be clever (obviously not very) by doing look ahead but this one seems tricky eg.

(?=[@]){1}[a-zA-Z@]+$
like image 928
PDStat Avatar asked Oct 29 '25 15:10

PDStat


2 Answers

The (?=[@]){1}[a-zA-Z@]+$ pattern matches any substring that starts with @ and then has zero or more letters or @ up to the end of the string. Look at what it matches.

You need to use

^(?=[^@]*@[^@]*$)(?=[^.]*\.)[a-zA-Z@.]+$

Or, if there must be also one dot (and no more than one) in the string

^(?=[^@]*@[^@]*$)(?=[^.]*\.[^.]*$)[a-zA-Z@.]+$

See the regex demo #1 and the regex demo #2.

Details

  • ^ - start of string
  • (?=[^@]*@[^@]*$) - requires only one @ and no more than one in string - a positive lookahead that requires 0+ chars other than @, a @, and again zero or more chars other than @ till the end of string
  • (?=[^.]*\.) - requires at least one dot - a positive lookahead that requires 0+ chars other than . and then a .
  • (?=[^.]*\.[^.]*$) - requires only one dot and no more than one in string - a positive lookahead that requires 0+ chars other than ., a ., and again zero or more chars other than . till the end of string
  • [a-zA-Z@.]+ - one or more ASCII letters, @ or .
  • $ - end of string.
like image 159
Wiktor Stribiżew Avatar answered Nov 01 '25 07:11

Wiktor Stribiżew


Another option could be using a single lookahead asserting @ and match a dot between 2 character classes, or the other way around asserting a dot and matching @

^(?=[^@]*@[^@]*$)[A-Za-z@]*\.[A-Za-z@]*$

Explanation

  • ^ Start of string
  • (?=[^@]*@[^@]*$) Assert only 1 @ char in the string
  • [A-Za-z@]*\.[A-Za-z@]* Match a dot between optionally repeating character classes each matching 1 out of A-Za-z@
  • $ End of string

Regex demo

For and . at least once anywhere in the string , you can allow matching a dot in the second character class:

^(?=[^@]*@[^@]*$)[A-Za-z@]*\.[A-Za-z@.]*$

Regex demo

like image 34
The fourth bird Avatar answered Nov 01 '25 05:11

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!