正则表达式 [\w-] 是什么意思? [英] What does the regular expression [\w-] mean?
问题描述
我查看了文档,但找不到 [\w-]
的含义.谁能告诉我 [\w-]
在 Ruby 中是什么意思?
I checked the documentation, and cannot find what [\w-]
means. Can anyone tell me what [\w-]
means in Ruby?
推荐答案
方括号 []
表示字符类.字符类将匹配其中的任何内容.
The square brackets []
denote a character class. A character class will match any of the things inside it.
\w
是一个特殊的类,称为单词字符".它是 [a-zA-Z0-9_]
的简写,所以它会匹配:
\w
is a special class called "word characters". It is shorthand for [a-zA-Z0-9_]
, so it will match:
a-z
(全部小写)A-Z
(全部大写)0-9
(所有数字)_
(下划线)
a-z
(all lowercase letters)A-Z
(all uppercase letters)0-9
(all digits)_
(an underscore)
您所询问的类 [\w-]
是一个由 \w
和 -
组成的类.所以它将匹配上面的列表,加上连字符(-
).
The class you are asking about, [\w-]
, is a class consisting of \w
and -
. So it will match the above list, plus hyphens (-
).
正如所写的那样,[\w-]
,这个正则表达式将匹配单个字符,只要它在上面的列表中,或者是一个破折号.
Exactly as written, [\w-]
, this regex would match a single character, as long as it's in the above list, or is a dash.
如果您要在末尾添加量词,例如[\w-]*
或 [\w-]+
,那么它将匹配以下任何字符串:
If you were to add a quantifier to the end, e.g. [\w-]*
or [\w-]+
, then it would match any of these strings:
fooBar9
foo-Bar9
foo-Bar-9
-foo-Bar---9abc__34ab12d
它会部分匹配这些:
foo,Bar9 # match 'foo' - the ',' stops the match
-foo-Bar---9*bc__34ab12d # match '-foo-Bar---9', the '*' stops the match
这篇关于正则表达式 [\w-] 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!