Javascript Javascript正则表达式“单空格字符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2429146/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:17:09  来源:igfitidea点击:

Javascript Regular Expression "Single Space Character"

javascriptregex

提问by Dennis D

I am learning javascript and I am analyzing existing codes.

我正在学习 javascript 并且正在分析现有代码。

In my JS reference book, it says to search on a single space use "\s"?

在我的 JS 参考书中,它说在单个空间上搜索使用“ \s”?

But I have came across the code

但我遇到了代码

obj.match(/Kobe Bryant/);

Instead of using \s, it uses the actual space?

\s它使用实际空间而不是 using ?

Why doesn't this generate an error?

为什么这不会产生错误?

回答by Gumbo

The character class \sdoes not just contain the space character but also other Unicode white space characters. \sis equivalent to this character class:

字符类\s不仅包含空格字符,还包含其他Unicode 空白字符\s相当于这个字符类:

[\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]

回答by SLaks

No. It is perfectly legal to include a literal space in a regex.

不。在正则表达式中包含文字空格是完全合法的。

However, it's not equivalent - \swill include any whitespace character, including tabs, non-breaking spaces, half-width spaces and other characters, whereas a literal space will only match the regular space character.

但是,它不是等效的 -\s将包括任何空白字符,包括制表符、不间断空格、半角空格和其他字符,而文字空格将仅匹配常规空格字符。

回答by Tatu Ulmanen

\smatches any whitespace character, including tabs etc. Sure you can use a literal space also without problems. Just like you can use [0-9]instead of \dto denote any digit.

\s匹配任何空白字符,包括制表符等。当然,您也可以毫无问题地使用文字空间。就像您可以使用[0-9]代替\d来表示任何数字一样。

回答by Hosam Aly

In addition to normal spaces, \smatches different kinds of white space characters, including tabs (and possibly newline characters, according to configuration). That said, matching with a normal space is certainly valid, especially in your case where it seems you want to match a name, which is normally separated by a normal space.

除了普通空格之外,\s匹配不同种类的空白字符,包括制表符(根据配置,可能还有换行符)。也就是说,与普通空格匹配当然是有效的,尤其是在您似乎想要匹配名称的情况下,该名称通常由普通空格分隔。