How can I negate part of a class in a regular expression?

时间:2016-03-02 10:50:58

标签: javascript regex

I want to negate part of a class in a regular expression. Let's say we have an expression accepting repeated big or small letters from a to z.

[a-zA-Z]+

How can I negate for example H letter?

I've tried this [a-zA-Z^H]+ but it doesn't block H.

I know we can do it otherwise, but I search for a general rule to negate inside of a class.

I use JavaScript flavor of regex.

UPDATE

Here's the more specific example. Here's the expression: [\w\-\–]. In .NET flavor it accepts unicode characters, but in JavaScript flavor it doesn't. There's a trick however to allow the expression to accept unicode chars too, \w must be replaced with this expression ([^\x00-\x7F]|\w).

The problem is - it can't be nested inside first expression ([\w\-\–]). That's why I'm asking how to make a negation of a part of a class.

2 个答案:

答案 0 :(得分:1)

通常你会使用类减法

[a-zA-Z--[H]]

对于不支持字符类减法(javascript)的引擎,您只需使用否定前瞻。

((?![H])[a-zA-Z])+

工作示例:https://regex101.com/r/sE6tH0/6

http://www.rexegg.com/regex-class-operations.html#subtraction_workaround

答案 1 :(得分:1)

将我的评论翻译成答案。这是一个正则表达式,可用于否定某些字符或范围:

/((?:[^\x00-\x7F]|[-\w–])+)/

RegEx Demo