Regex - Match a string which has zero or one spaces

java, regex

Solution

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)

Problem

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.

Original source