George
George

Reputation: 86

Regex to match one character exactly one time anywhere inside a string

I want to match the symbol @ inside a string. It doesn't matter if it is at the beginning, at the middle or at the end of string or anywhere inside it. What matters is to just match it only 0 or 1 times.

I thought of something like this:

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

But definitely doesn't work because even though it matches the symbol @ once, it can match it only inside the string.

@foobar Valid
foo@bar Valid
foobar@ Valid
fooba@r Valid

but

@@foobar Invalid
@foo@bar Invalid
foo@b@ar Invalid

Upvotes: 5

Views: 24541

Answers (1)

Allan
Allan

Reputation: 12438

You can use the following regex:

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

to forbid to have more than one @ in your input string.

Tested:

https://regex101.com/r/H4hXF5/1

if you need to match also string without the @ in it add a ? just after it in the regex:

^[^@]*@?[^@]*$

this will also match string abc for example

explanations:

  • ^ beginning of line
  • [^@]* then all char except the @ taken 0 to N times
  • @ then one @ char
  • [^@]* same as step2
  • $ ending of the line
  • ? to have the character before it become optional

Upvotes: 8

Related Questions