I'm trying to match a string which starts with @, can contain any amount of letters or numbers but can only contain a maximum of one space (or zero spaces). So far I have
@([A-Za-z0-9]+)
which matches the characters but without the space. I think I need \s{0,1} but I'm not sure where to put it.. Can anyone help?
Thanks.
Assuming you only care about spaces in the word, not leading or trailing then you could use this:
@[A-Za-z0-9]* ?[A-Za-z0-9]*
Explanation:
@
Starts with literal @
[A-Za-z0-9]
Any letter or number
*
Letter or number can be length {0,infinity}
?
Space char, 0 or one times
[A-Za-z0-9]*
Any number of trailing letters or spaces after the space (if there is one)
You could try the below regex to match the words which starts with @
follwed by any number of letters or numbers with an optional space,
^@[a-zA-Z0-9]+ ?[a-zA-Z0-9]*$
DEMO
Java pattern would be,
"^@[a-zA-Z0-9]+ ?[a-zA-Z0-9]*$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With