简体   繁体   English

正则表达式和字符串

[英]regex and string

Consider the following: 考虑以下:

string keywords = "(load|save|close)";
Regex x = new Regex(@"\b"+keywords+"\b");

I get no matches. 我没有比赛。 However, if I do this: 但是,如果我这样做:

Regex x = new Regex(@"\b(load|save|close)\b");

I get matches. 我得到火柴。 How come the former doesn't work, and how can I fix this? 前者怎么不起作用,我该如何解决? Basically, I want the keywords to be configurable so I placed them in a string. 基本上,我希望关键字是可配置的,因此我将它们放在字符串中。

The last \\b in the first code snippet needs a verbatim string specifier ( @ ) in front of it as well as it is a seperate string instance. 第一个代码段中的最后一个\\b在其前面需要一个逐字字符串说明符( @ ),并且它是一个单独的字符串实例。

string keywords = "(load|save|close)"; 
Regex x = new Regex(@"\b"+keywords+@"\b");  

您缺少另一个逐字字符串说明符( @末尾\\b前缀):

Regex x = new Regex(@"\b" + keywords + @"\b");
Regex x = new Regex(@"\b"+keywords+@"\b");

您在第二个"\\b"之前忘记了其他@

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

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