正则表达式单词边界不包括连字符 [英] regex word boundary excluding the hyphen
问题描述
我需要一个正则表达式来匹配以单词边界结尾的表达式,但它不将连字符视为边界.即获取所有匹配的表达式
i need a regex that matches an expression ending with a word boundary, but which does not consider the hyphen as a boundary. i.e. get all expressions matched by
type ([a-z])\b
但不匹配例如
type a-1
重新表述:我想要一个等效的单词边界运算符 \b,它不使用单词字符类 [A-Za-z0-9_]
,而是使用扩展类:[A-Za-z0-9_-]
to rephrase: i want an equivalent of the word boundary operator \b which instead of using the word character class [A-Za-z0-9_]
, uses the extended class: [A-Za-z0-9_-]
推荐答案
您可以为此使用前瞻,最短的是使用否定前瞻:
You can use a lookahead for this, the shortest would be to use a negative lookahead:
type ([a-z])(?![\w-])
(?![\w-])
表示如果下一个字符在 \w
中或者是 -
则匹配失败>".
(?![\w-])
would mean "fail the match if the next character is in \w
or is a -
".
这是一个使用正常前瞻的选项:
Here is an option that uses a normal lookahead:
type ([a-z])(?=[^\w-]|$)
您可以将 (?=[^\w-]|$)
读作仅匹配字符类 [\w-]
,或者这是字符串的结尾".
You can read (?=[^\w-]|$)
as "only match if the next character is not in the character class [\w-]
, or this is the end of the string".
看看它是否有效:http://www.rubular.com/r/NHYhv72znm
这篇关于正则表达式单词边界不包括连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!