Pergunta

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?

Foi útil?

Solução 2

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

[.,/)]

Outras dicas

\) is the correct way for escaping a paranthesis. Make sure you are properly escaping the \(\\) in the string literal.

Alternative Solution

Instead of a set, it can be easier to use the hex code. This code does not need a C# escape.

Example

The hex code for a ( is \x28 and its counterpart ) is \x29.

To use in a pattern would look exactly like this to find anything between the parenthesis

\x28[^\x29]+\x29 which escaped would be \)[^)]+\)

or searched in a different way:

\x28.+?\x29

Which all previous patterns would be able to match:

(abc)


I also use this in my regex patterns for the double quotes (\x22) and the single quote (\x27) which is the apostrophe.

It just makes working with the regex patterns easier while C# coding.

Your regex should look like this: (\.|,|\/|\))

Test it out with http://rubular.com/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top