转义正则表达式中的括号 [英] Escaping Parentheses in Regex

查看:113
本文介绍了转义正则表达式中的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式,它在末尾有可选的锚点,例如

I have a regex which has optional anchors at the end e.g.

(\.|,|\/)

我正在尝试为此添加)",但如果我将其转义

I am trying to add ")" to this but if I escape it

(/.|,|\/|\))

未找到,如果不转义,则将其视为表达式的一部分并失败,因为没有打开的括号.我怎样才能逃脱它以便它被视为一个字符并被发现?

it isn't found and if don't escape it is treated as part of the expression and fails since there is no open parens. How can I escape it so it is treated as a character and found?

推荐答案

如果要匹配一组字符中的一个,最好使用 字符类.在这样的类中,大多数转义规则都不适用.

If you want to match one of a set of character, it's best to use a character class. And within such a class, most escaping rules don't apply.

因此要匹配点、逗号、斜线或右括号,您可以使用

So to match a dot, comma, slash or closing parenthesis, you can use

[.,/)]

这篇关于转义正则表达式中的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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