crazyfool
crazyfool

Reputation: 1463

Regex - Match a string which has zero or one spaces

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.

Upvotes: 9

Views: 16386

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174706

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]*$"

Upvotes: 1

Adam Yost
Adam Yost

Reputation: 3625

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)

Upvotes: 12

Braj
Braj

Reputation: 46841

Is this what you needed?

@[A-Za-z0-9]+(?:\s?)[A-Za-z0-9]+

Online demo

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can use this regex with negative lookahead:

^@((?!(?:\S* ){2})[A-Za-z0-9 ]+)$

Upvotes: 0

Related Questions