如何在正则表达式中添加连字符 [英] How to add hyphen to regex

查看:470
本文介绍了如何在正则表达式中添加连字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这种模式

(\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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆