RegExp只允许单词之间有一个空格

RegExp which allow only one space in between words

本文关键字:有一个 空格 之间 许单词 RegExp      更新时间:2023-09-26

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

使用RegExp:

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

测试简单的:

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+)+

测试用例(为了清晰起见添加了"s"):

"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)

尝试使用代码,我给你和javascript实现,我希望它会为你好HTML代码

<input type="test" class="name" />

Javascript代码:

$('.name').keyup(function() {
    var $th = $(this);
    $th.val($th.val().replace(/('s{2,})|[^a-zA-Z']/g, ' '));
    $th.val($th.val().replace(/^'s*/, ''));
    });

此代码不允许字符或单词之间有一个以上的空格。点击此处查看JsFiddle链接

试试这个:

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

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

顺便说一句,当您提供regexp字面量时,不需要使用new RegExp。只有在将字符串转换为RegExp时才需要。

试试这个正则表达式

/^('w+)('s+)/

和你的代码:

result = inputString.replace(/^('w+)('s+)?/g, "$1");
相关文章: