Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match a string which has zero or one spaces

Tags:

java

regex

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.

like image 663
crazyfool Avatar asked Jul 11 '14 14:07

crazyfool


2 Answers

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)

like image 112
Adam Yost Avatar answered Sep 27 '22 18:09

Adam Yost


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]*$"
like image 37
Avinash Raj Avatar answered Sep 27 '22 20:09

Avinash Raj