正则表达式匹配空间但不是任何非单词字符Javascript

时间:2017-05-01 13:18:15

标签: javascript regex

我想用 javascript 编写一个允许任何字符或空格但不包含任何其他非单词字符的文字:

david johan // pass
david johan mark // pass 
david@# johan // doesn't pass 

我用过这个

/^(([a-zA-Z]{3,30})+[ ]+([a-zA-Z]{3,30})+)+$/ 

但它不起作用 有什么建议 ?

3 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式:

<form class="form-horizontal">
<div class="row">
    <div class="form-group col-sm-6">
        <input type="text" class="form-control input-lg" placeholder="Your Title">
    </div>
    <div class="form-group col-sm-6">
        <input type="text" class="form-control input-lg" placeholder="Your Description">
    </div>
</div>
</form>

或在Javascript中:

<form class="form-horizontal">
<div class="row">
    <div class="form-group col-xs-6">
        <input type="text" class="form-control input-lg" placeholder="Your Title">
    </div>
    <div class="form-group col-xs-6">
        <input type="text" class="form-control input-lg" placeholder="Your Description">
    </div>
</div>
</form>

答案 1 :(得分:1)

很难准确说出你的目标,但我认为这样做会很好:

/^([a-z0-9]|\s)*$/i

^表示需要从括号中的代码开始,而$表示它也需要以其中一个字符结束。 *表示前面表达式中的0个或更多,而parens中的位表示范围a-z或数字0-9或(|)任何空格字符,制表符中的任何字母,新行等(\s)。

它应匹配任何字母或数字,并且它上面也有不区分大小写的标记(i),它也会占用空格。

如果可以包含_,那么您可以使用/^(\w|\s)*$/

答案 2 :(得分:0)

尝试此模式\w+\s+\w+

Demo

console.log(/\w+\s+\w+/g.test("david johan"))
console.log(/\w+\s+\w+/g.test("david johan mark "))
console.log(/\w+\s+\w+/g.test("david@# johan"))    
console.log(/\w+\s+\w+/g.test("david @# johan"))
console.log(/\w+\s+\w+/g.test("this should not match!"));

相关问题