RegExp,只允许在单词之间留一个空格

时间:2013-05-26 05:31:40

标签: javascript regex

我正在尝试编写一个正则表达式来从单词的开头处删除空格,而不是在单词后面的单个空格中删除空格。

使用RegExp:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);

测试Exapmle:

1) wordX[space] - Should be allowed 
2) [space] - Should not be allowed 
3) WrodX[space][space]wordX - Should be allowed 
4) WrodX[space][space][space]wordX - Should be allowed 
5) WrodX[space][space][space][space] - Should be not be allowed 
6) WrodX[space][space] - Allowed with only one space the moment another space is entered **should not be allowed** 

3 个答案:

答案 0 :(得分:3)

试试这个:

^\s*\w+(\s?$|\s{2,}\w+)+

测试用例(为了清楚起见,添加了“):

"word"         - allowed (match==true)
"word "        - allowed (match==true)
"word  word"   - allowed (match==true)
"word   word"  - allowed (match==true)
" "            - not allowed (match==false)
"word  "       - not allowed (match==false)
"word    "     - not allowed (match==false)
" word"        - allowed (match==true)
"  word"       - allowed (match==true)
"  word "      - allowed (match==true)
"  word  word" - allowed (match==true)

See demo here.

答案 1 :(得分:0)

试试这个:

var re = /\S\s?$/;

这匹配非空格,后跟字符串末尾最多一个空格。

顺便说一下,当你提供正则表达式文字时,不需要使用new RegExp。只有在将字符串转换为RegExp时才需要。

答案 2 :(得分:0)

试试这个正则表达式

/^(\w+)(\s+)/

和你的代码:

result = inputString.replace(/^(\w+)(\s+)?/g, "$1");