RegExp,只允许在单词之间留一个空格 [英] RegExp which allow only one space in between words
本文介绍了RegExp,只允许在单词之间留一个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个正则表达式来从单词的开头删除空格,而不是在单词后面的单个空格中删除空格。
I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.
使用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**
推荐答案
试试这个:
^\s*\w+(\s?$|\s{2,}\w+)+
测试用例(为了清晰起见,添加了):
Test cases ("s added for clarity):
"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)
这篇关于RegExp,只允许在单词之间留一个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文