如何使用javascript正则表达式允许字符串中最多3个空格

时间:2013-11-06 22:25:55

标签: javascript

使用java脚本正则表达式

允许字符串中最多三个空格

我尝试了以下

<script type="text/javascript">
var mainStr = "Hello World";
var pattern= /^(?=[^ ]* ?[^ ]*(?: [^ ]*)?$)(?=[^-]*-?[^-]*$)(?=[^']*'?[^']*$)[a-zA-Z '-]*$/; 
if(pattern.test(mainStr)){
 alert("matched");
}else{
 alert("not matched");

}
</script>

2 个答案:

答案 0 :(得分:1)

以下正则表达式匹配0-3个空白字符。

\s{0,3}

以下正则表达式匹配最多包含3个空格字符的字符串。

^[^\s]+\s?[^\s]*\s?[^\s]*\s?[^\s]*$

示例:

"ab" - (match)
"a b" - (match)
"a b c" - (match)
"a b c d" - (match)
"a b c d e" - (doesn't match)
"a b c d e f" - (doesn't match)

(还在等待提问者的例子!)

答案 1 :(得分:1)

你需要一个正则表达式吗

如果您想要做的唯一目的是在字符串中的任何位置允许最多3个空格 - 为什么不简单地比较删除所有空格(或空格字符\s之前和之后字符串的长度,如果相关的)?如果差异超过3个字符 - 它包含3个以上的空格。

e.g。

var mainStr = "Hello Wor l d";

if(mainStr.replace(/ /g, '').length > (mainStr.length - 3)) {
    alert("matched");
}else{
    alert("not matched");
}

如果您的要求更具体 - 您需要澄清(编辑问题),否则在不需要时不要使用正则表达式。