我可以使用什么regex来匹配每个单词之间的字母、数字和空格?

时间:2022-09-27 19:27:49

How can I create a regex expression that will match only letters and numbers, and one space between each word?

我如何创建一个regex表达式,它只匹配字母和数字,每个单词之间有一个空格?

Good Examples:

很好的例子:

Amazing

Hello World

I am 500 years old

Bad Examples:

坏的例子:

Hello  world

I am 500 years      old.

I    am   Chuck Norris

6 个解决方案

#1


23  

Most regex implementations support named character classes:

大多数regex实现支持命名的字符类:

^[[:alnum:]]+( [[:alnum:]]+)*$

You could be clever though a little less clear and simplify this to:

你可以把它简化成:

^([[:alnum:]]+ ?)*$

FYI, the second one allows a spurious space character at the end of the string. If you don't want that stick with the first regex.

顺便说一句,第二个字符串允许字符串末尾有一个伪空格字符。如果你不想要第一个正则表达式。

Also as other posters said, if [[:alnum:]] doesn't work for you then you can use [A-Za-z0-9] instead.

同样,正如其他海报所说,如果[[:alnum:]]对你不起作用,那么你可以使用[A-Za-z0-9]。

#2


7  

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

#3


6  

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

its works

其作品

#4


2  

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

#5


1  

(?:[a-zA-Z0-9]+[ ])+[a-zA-Z0-9]+

If I understand you correctly the above regex should work. See screenshot below:

如果我理解正确,上面的regex应该可以工作。见下面的截图:

screenshot http://img136.imageshack.us/img136/6871/screenshotkiki056.png

截图http://img136.imageshack.us/img136/6871/screenshotkiki056.png

#6


-1  

This would match a word

这是一个词

'[a-zA-Z0-9]+\ ?'

#1


23  

Most regex implementations support named character classes:

大多数regex实现支持命名的字符类:

^[[:alnum:]]+( [[:alnum:]]+)*$

You could be clever though a little less clear and simplify this to:

你可以把它简化成:

^([[:alnum:]]+ ?)*$

FYI, the second one allows a spurious space character at the end of the string. If you don't want that stick with the first regex.

顺便说一句,第二个字符串允许字符串末尾有一个伪空格字符。如果你不想要第一个正则表达式。

Also as other posters said, if [[:alnum:]] doesn't work for you then you can use [A-Za-z0-9] instead.

同样,正如其他海报所说,如果[[:alnum:]]对你不起作用,那么你可以使用[A-Za-z0-9]。

#2


7  

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

#3


6  

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

its works

其作品

#4


2  

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

#5


1  

(?:[a-zA-Z0-9]+[ ])+[a-zA-Z0-9]+

If I understand you correctly the above regex should work. See screenshot below:

如果我理解正确,上面的regex应该可以工作。见下面的截图:

screenshot http://img136.imageshack.us/img136/6871/screenshotkiki056.png

截图http://img136.imageshack.us/img136/6871/screenshotkiki056.png

#6


-1  

This would match a word

这是一个词

'[a-zA-Z0-9]+\ ?'