逃避左括号C#正则表达式 [英] Escape Left Bracket C# Regex

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

问题描述

我有一个字符串,格式如下:

I have a string in the following format:

prm.Add( "blah", "blah" ); 

我正在寻找使用正则表达式来提取第一个blah。
为了做到这一点,我雕刻前半部分,然后是后半部分。

I am looking to use regex to extract the first "blah". To do this I am carving the front half off and then the back half.

正在使用正则表达式来摆脱prm.Add(是:

The regex I'm using to get rid of "prm.Add( " is:

"prm.Add\([ ]*"

其他线程似乎表示逃避角色在paranthesis之前是可以接受的,但VS抱怨说我有一个无效的转义字符序列(。
如果我使用:

Other threads seem to indicate that escape characters before paranthesis would be acceptable. However VS complains that I have an invalid escape charcter sequence "(". If I use:

"prm.Add([ ]*" 

没有关闭的例证。

我意识到我可以通过在prm.Add()上使用Regex.Escape来解决这个问题,但这并不是非常优雅

I realise I can get around this by using Regex.Escape on the "prm.Add(". But this isn't really very elegant.

我的正则表达式语法错误或VS2010不接受转义的括号?

Have I got my regex syntax wrong or does VS2010 not accept escapes of brackets?

推荐答案

您只需转义反斜杠即可编译器了解:prm.Add\\([] * @prm.Add\([] *

You just have to escape the backslash as well for the compiler to understand: "prm.Add\\([ ]*" or @"prm.Add\([ ]*"

否则,编译器无法理解\\\
- 作者想要什么?换行符或字符串\按原样?

Otherwise the compiler couldn't understand things like "\n" - what does the author want? A line break or the string "\n" as-is?

但是我会尝试使其更具动态性,例如没有假设空格字符在那里。

But I'd try to make it more dynamic, e.g. not assuming a space character being there.

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

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