C#正则表达式搜索包含周围括号的文本字符串

时间:2022-06-01 21:29:20

I would like to search a string for '[E1010]' or '[E1011]' or '[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.

我想在字符串中搜索'[E1010]'或'[E1011]'或'[E1012]'。目前,我只能在不使用括号[]的情况下成功搜索。如何调整我的正则表达式以包括括号中包含的文本,因为它在我的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...

    }

2 个解决方案

#1


1  

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”的内容,也可以使用“\\”,其中“\ *”是正则表达式选项。

#2


2  

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

请注意,添加括号后,不再需要单词边界。另请注意,您无需转义方括号

#1


1  

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”的内容,也可以使用“\\”,其中“\ *”是正则表达式选项。

#2


2  

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

请注意,添加括号后,不再需要单词边界。另请注意,您无需转义方括号