2012-01-20 78 views
7

我需要一个符合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

出于好奇,你尝试寻找这首? –

+0

是的,我完全忘了\ s的否定版本..虽然.. doh!感谢所有回复的人! –

+0

而不是使用正则表达式,你也可以测试'if(str.trim()){//匹配}' – Shmiddty

回答

14

这会查找至少一个非空白字符。

/\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 
1
/^\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/

1

试试这个表达式:

/\S+/ 

\ S表示任何非空白字符。

+2

不需要'+'。 – Phrogz

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

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

[我不是我]的回答是最好的:

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

或者你可以这样做:

/[^\s]/.test("foo"); 
相关问题