除所有空格外,匹配任何内容的正则表达式

20

我需要一个(符合javascript标准的)正则表达式,它能匹配任何字符串,但不包括只包含空格的字符串。以下是示例:

" "         (one space) => doesn't match
"    "      (multiple adjacent spaces) => doesn't match
"foo"       (no whitespace) => matches
"foo bar"   (whitespace between non-whitespace) => matches
"foo  "     (trailing whitespace) => matches
"  foo"     (leading whitespace) => matches
"  foo   "  (leading and trailing whitespace) => matches

4
有点好奇,你先尝试搜索了这个吗? - Dave Newton
是的,我忘记了\s的否定版本..哎呀!感谢所有回复的人! - Bill Dami
不必使用正则表达式,你也可以测试if(str.trim()){ //匹配 } - Shmiddty
5个回答

28

这个代码会查找至少一个非空格字符。

/\S/.test("   ");      // false
/\S/.test(" ");        // false
/\S/.test("");         // false


/\S/.test("foo");      // true
/\S/.test("foo bar");  // true
/\S/.test("foo  ");    // true
/\S/.test("  foo");    // true
/\S/.test("  foo   "); // true

我猜我假定一个空字符串应该被视为仅包含空格。

如果一个空字符串 (从技术角度来讲并不包含所有空格,因为它什么也没有) 应该通过测试,那么将其改为...

/\S|^$/.test("  ");      // false

/\S|^$/.test("");        // true
/\S|^$/.test("  foo  "); // true

8

尝试使用这个表达式:

/\S+/

\S代表任何非空格字符。


2
/^\s*\S+(\s?\S)*\s*$/

演示:

var regex = /^\s*\S+(\s?\S)*\s*$/;
var cases = [" ","   ","foo","foo bar","foo  ","  foo","  foo   "];
for(var i=0,l=cases.length;i<l;i++)
    {
        if(regex.test(cases[i]))
            console.log(cases[i]+' matches');
        else
            console.log(cases[i]+' doesn\'t match');

    }

工作演示: http://jsfiddle.net/PNtfH/1/


2
< p > [Am not I am] 的回答是最好的:

/\S/.test("foo");

或者你可以这样做:

/[^\s]/.test("foo");

1
if (myStr.replace(/\s+/g,'').length){
  // has content
}

if (/\S/.test(myStr)){
  // has content
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接