正则表达式,除所有空格外,均与其他任何内容匹配 [英] Regex that matches anything except for all whitespace

查看:84
本文介绍了正则表达式,除所有空格外,均与其他任何内容匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个(与javascript兼容的)正则表达式,它将匹配除仅包含空格的字符串以外的任何字符串.案例:

I need a (javascript compliant) regex that will match any string except a string that contains only whitespace. Cases:

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

推荐答案

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

This looks for at least one non whitespace character.

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


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


I guess I'm assuming that an empty string should be consider whitespace only.

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

If an empty string (which technically doesn't contain all whitespace, because it contains nothing) should pass the test, then change it to...

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

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

这篇关于正则表达式,除所有空格外,均与其他任何内容匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆