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

cod*_*man 6 javascript regex

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

使用RegExp:

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

测试Exapmle:

1) test[space]ing - Should be allowed 
2) testing - Should be allowed 
3) [space]testing - Should not be allowed 
4) testing[space] - Should be allowed but have to trim it 
5) testing[space][space] - should be allowed but have to trim it 
Run Code Online (Sandbox Code Playgroud)

只允许一个空格.可能吗?

Mic*_*šna 12

要匹配,你需要什么,你可以使用

var re = /^([a-zA-Z0-9]+\s)*[a-zA-Z0-9]+$/;
Run Code Online (Sandbox Code Playgroud)

也许你可以缩短这一点,但它匹配_以及

var re = /^(\w+\s)*\w+$/;
Run Code Online (Sandbox Code Playgroud)

  • @falsetru 这就是 OP 在正则表达式中有 `([a-zA-Z0-9]+\s?)*` 的重点 (2认同)

fal*_*tru 11

function validate(s) {
    if (/^(\w+\s?)*\s*$/.test(s)) {
        return s.replace(/\s+$/, '');
    }
    return 'NOT ALLOWED';
}
validate('test ing')    // => 'test ing'
validate('testing')     // => 'testing'
validate(' testing')    // => 'NOT ALLOWED'
validate('testing ')    // => 'testing'
validate('testing  ')   // => 'testing'
validate('test ing  ')  // => 'test ing'
Run Code Online (Sandbox Code Playgroud)

new RegExp(..)如果您使用正则表达式文字,BTW 是多余的.


Row*_*ski 6

此选项不允许前后有空格,单词之间只能有一个空格。请随意添加您想要的任何特殊字符。

^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]+$
Run Code Online (Sandbox Code Playgroud)

演示在这里