2012-01-20 77 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"); 
相關問題