如何在正则表达式中添加连字符 [英] How to add hyphen to regex
问题描述
我遇到了这种模式
(\w+)
和 http://gskinner.com/RegExr/网站上,我了解\w
=匹配字母数字字符和下划线,+
=匹配先前的标记1次或多次(不确定确切的含义).
and from http://gskinner.com/RegExr/ site I understand that \w
= match alpha-numeric characters and underscores, and +
= match previous token 1 or more times (not exactly sure what that means).
如何将连字符添加到列表中?
How can I add the hyphen character to the list?
我尝试了(\w\-+)
,但是它不起作用,我没有找到任何匹配项...
I tried (\w\-+)
but it doesn't work, I don't get any match ...
推荐答案
您需要一个字符类,用[...]
表示.然后可以在字符类中使用\w
并可以添加更多字符:
You need a character class, denoted by [...]
. \w
can then be used in the character class and more characters can be added:
[\w-]
但是请小心,如果您添加更多字符以进行匹配.连字符减号在类中必须为 first 或 last ,以避免将其解释为范围(或相应地对其进行转义).
Careful though, if you add more characters to match. The hyphen-minus needs to be first or last in a class to avoid interpreting it as a range (or escape it accordingly).
+
是一个量词,因此它跟随一个标记(整个字符类是单个标记[\w
]):
The +
is a quantifier, so it goes after a token (where the whole character class is a single token [as is \w
]):
([\w-]+)
这篇关于如何在正则表达式中添加连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!