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

Bil*_*ami 14 javascript regex whitespace

我需要一个(符合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
Run Code Online (Sandbox Code Playgroud)

小智 22

这将查找至少一个非空白字符.

/\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
Run Code Online (Sandbox Code Playgroud)

我想我假设一个空字符串应该只考虑空格.

如果一个空字符串(技术上不包含所有空格,因为它不包含任何内容)应该通过测试,然后将其更改为...

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

/\S|^$/.test("");        // true
/\S|^$/.test("  foo  "); // true
Run Code Online (Sandbox Code Playgroud)


小智 8

试试这个表达式:

/\S+/
Run Code Online (Sandbox Code Playgroud)

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