2012-01-20 10 views
7

Ho bisogno di un'espressione regolare (javascript compatibile) che possa corrispondere a qualsiasi stringa tranne una stringa che contiene solo spazi bianchi. Casi:Regex che corrisponde a qualsiasi cosa eccetto per tutti gli spazi bianchi

" "   (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

Per curiosità, hai provato a cercare per questa prima? –

+0

Sì, l'ho fatto, mi sono completamente dimenticato della versione negata di \ s però .. doh! Grazie a tutti quelli che hanno risposto! –

+0

Invece di usare espressioni regolari, si potrebbe anche testare 'if (str.trim()) {// corrisponde}' – Shmiddty

risposta

14

Questo cerca almeno un carattere non di spazi vuoti.

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

Credo di essere assumendo che una stringa vuota deve essere considerare spazi bianchi solo.

Se una stringa vuota (che tecnicamente non contiene tutti gli spazi vuoti, in quanto contiene niente) dovrebbe superare il test, quindi passarlo ...

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

/\S|^$/.test("");  // true 
/\S|^$/.test(" foo "); // true 
1
/^\s*\S+(\s?\S)*\s*$/ 

demo:

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'); 

    } 

demo funzionante: http://jsfiddle.net/PNtfH/1/

1

Prova questa espressione:

/\S+/ 

\ S indica qualsiasi carattere non di spazi vuoti.

+2

Non c'è bisogno di '+'. – Phrogz

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

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

[Non sono io] 's risposta è il migliore:

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

In alternativa si può fare:

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