简体   繁体   English

C#正则表达式搜索字符串以查找文本,包括方括号

[英]C# Regex search string for text including surrounding brackets

I would like to search a string for '[E1010]' or '[E1011]' or '[E1012]'. 我想在字符串中搜索“ [E1010]”或“ [E1011]”或“ [E1012]”。 Currently, I can only successfully search without using the brackets []. 目前,我只能在不使用方括号[]的情况下成功搜索。 How can I adjust my regex to include the texting surrounded by the brackets as it is in my sClientError variable. 如何调整我的正则表达式,使其包含在sClientError变量中的方括号括起来的文本。

Thanks! 谢谢!

string sClientErrors = "Bla Blah \"30\" [E1011]\r\nBlah Blah"44\" [E1012]";

    Regex myRegexE10 = new Regex(@"\bE1010\b");
    Regex myRegexE11 = new Regex(@"\bE1011\b");
    Regex myRegexE12 = new Regex(@"\bE1012\b");

    if (myRegexE10.IsMatch(sClientErrors) || myRegexE11.IsMatch(sClientErrors) || myRegexE12.IsMatch(sClientErrors))
    {

           // do code here...

    }

By adding the brackets: 通过添加括号:

Regex myRegexE10 = new Regex(@"\[E1010]");

or 要么

Regex myRegexE1x = new Regex(@"\[E101[012]]");
if (myRegexE1x.IsMatch(sClientErrors)) { ... 

Note that once you add the brackets, word boundaries are no longer necessary. 请注意,一旦添加了方括号,就不再需要单词边界。 Note too that you don't need to escape closing square brackets 还要注意,您无需转义右方括号

You can put a "\\" if front of a character you want to include, so you would use: 您可以在要包含的字符前面加上“ \\”,因此可以使用:

Regex myRegexE10 = new Regex(@"\[\bE1010\b\]")

You can also use "\\\\" if you needed to find something like "\\s", where "\\*" is a Regex option. 如果需要查找类似“ \\ s”的内容,也可以使用“ \\\\”,其中“ \\ *”是正则表达式选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM