javascript 正则表达式匹配除所有空格之外的任何内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8947866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex that matches anything except for all whitespace
提问by Bill Dami
I need a (javascript compliant) regex that will match any string except a string that contains only whitespace. Cases:
我需要一个(符合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
回答by
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 assumingthat 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
回答by Joe A
Try this expression:
试试这个表达:
/\S+/
\S mean any non-whitespace character.
\S 表示任何非空白字符。
回答by gion_13
/^\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');
}
working demo : http://jsfiddle.net/PNtfH/1/
工作演示:http: //jsfiddle.net/PNtfH/1/
回答by Phrogz
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}
回答by vol7ron
[Am not I am]'s answer is the best:
[Am not I am] 的回答是最好的:
/\S/.test("foo");
Alternatively you can do:
或者你可以这样做:
/[^\s]/.test("foo");