Regular expression to allow spaces between words

2020-01-24 03:38发布

I want a regular expression that prevents symbols and only allows letters and numbers. The regex below works great, but it doesn't allow for spaces between words.

^[a-zA-Z0-9_]*$

For example, when using this regular expression "HelloWorld" is fine, but "Hello World" does not match.

How can I tweak it to allow spaces?

13条回答
Evening l夕情丶
2楼-- · 2020-01-24 03:50

Just add a space to end of your regex pattern as follows:

[a-zA-Z0-9_ ]
查看更多
我命由我不由天
3楼-- · 2020-01-24 03:53

I find this one works well for a "FullName":

([a-z',.-]+( [a-z',.-]+)*){1,70}/
查看更多
Anthone
4楼-- · 2020-01-24 03:59

One possibility would be to just add the space into you character class, like acheong87 suggested, this depends on how strict you are on your pattern, because this would also allow a string starting with 5 spaces, or strings consisting only of spaces.

The other possibility is to define a pattern:

I will use \w this is in most regex flavours the same than [a-zA-Z0-9_] (in some it is Unicode based)

^\w+( \w+)*$

This will allow a series of at least one word and the words are divided by spaces.

^ Match the start of the string

\w+ Match a series of at least one word character

( \w+)* is a group that is repeated 0 or more times. In the group it expects a space followed by a series of at least one word character

$ matches the end of the string

查看更多
三岁会撩人
5楼-- · 2020-01-24 03:59

For alphabets only:

^([a-zA-Z])+(\s)+[a-zA-Z]+$

For alphanumeric value and _:

^(\w)+(\s)+\w+$
查看更多
霸刀☆藐视天下
6楼-- · 2020-01-24 04:01

Had a good look at many of these supposed answers...

...and bupkis after scouring Stack Overflow as well as other sites for a regex that matches any string with no starting or trailing white-space and only a single space between strictly alpha character words.

^[a-zA-Z]+[(?<=\d\s]([a-zA-Z]+\s)*[a-zA-Z]+$

Thus easily modified to alphanumeric:

^[a-zA-Z0-9]+[(?<=\d\s]([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$

(This does not match single words but just use a switch/if-else with a simple ^[a-zA-Z0-9]+$ if you need to catch single words in addition.)

enjoy :D

查看更多
该账号已被封号
7楼-- · 2020-01-24 04:02

Try this: (Python version)

"(A-Za-z0-9 ){2, 25}"

change the upper limit based on your data set

查看更多
登录 后发表回答