开发者

How to match a single space total not just a single space using regular expressions

开发者 https://www.devze.com 2023-03-09 09:36 出处:网络
Here is what I currently have, this will match alphanumerical characters and space: ^[a-z0-9\\s]+$ What I would like to do is to ensure that there will only be a match if there is no more than one

Here is what I currently have, this will match alphanumerical characters and space:

^[a-z0-9\s]+$

What I would like to do is to ensure that there will only be a match if there is no more than one (1) space. The above will match "This is a test", but I would only want it to match if the input is "This isatest", or "T hisisatest". As soon as there is more开发者_JS百科 than one space total it will no longer match.

Ideally it would also not match if the space is leading or trailing, but that's just icing.

EDIT: The idea is that this will be used to verify account names upon account creation. The account name may only contain a Latin letter, a number, and a single space. However, it could be all letters or all numbers, the space is not required. This is definitely about space and not whitespace.


Will allow atmost one space in between.

^[a-zA-Z0-9]+\s?[a-zA-Z0-9]+$

Will allow exactly one space in between

^[a-zA-Z0-9]+\s[a-zA-Z0-9]+$

EDIT1:

Above solutions does not accept single character strings.

The below solutions also matches single character strings

^[a-zA-Z0-9]+([ ][a-zA-Z0-9]+)?$


First clean the username by trimming leading and trailing whitespace.

^[a-z0-9]+(?: [a-z0-9]+)?$


Should be as simple as this. Matches 0 or 1 whitespace character in the middle of the text. Although it matches tabs too.

[a-z0-9]+\s{0,1}[a-z0-9]+


It's fairly easy, just build it in chunks.

^[a-z0-9]+(?: [a-z0-9]+)?$

One or more alphanumerics, then an optional group consisting of a single space followed by one or more alphanumerics. (BTW, \s matches a whitespace character, not a space. That is, it actually matches [ \t\n]. Which do you actually want?)


Try:

^[a-z0-9]+(?: [a-z0-9]+)?$

(Edited: your follow-up suggests you want to check for a space rather than for whitespace).

0

精彩评论

暂无评论...
验证码 换一张
取 消