Javascript 匹配除所有空格以外的任何内容的正则表达式
我需要一个(符合javascript的)正则表达式,它将匹配除只包含空格的字符串之外的任何字符串。案例:Javascript 匹配除所有空格以外的任何内容的正则表达式,javascript,regex,whitespace,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) =>
" " (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
这将查找至少一个非空白字符
/\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
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}
我猜我假设一个空字符串应该只考虑空白。< /P> 如果一个空字符串(技术上不包含所有空格,因为它不包含任何内容)应该通过测试,那么将其更改为
/\S|^$/.test(" "); // false
/\S|^$/.test(""); // true
/\S|^$/.test(" foo "); // true
演示:
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');
}
var regex=/^\s*\s+(\s?\s)*\s*$/;
变量案例=[“”、“”、“foo”、“foo-bar”、“foo”、“foo”、“foo”、“foo”];
对于(var i=0,l=cases.length;i请尝试以下表达式:
/\S+/
\S表示任何非空白字符。[Am not I Am]的答案是最好的:
/\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
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}
/\S/.test("foo");
或者,您可以执行以下操作:
/[^\s]/.test("foo");
出于好奇,您是否先尝试搜索此项?是的,我确实尝试过,但完全忘记了\s的否定版本..doh!感谢所有回复的人!您还可以测试if(str.trim()){//matches}