简体   繁体   English

这个正则表达式怎么了

[英]what's wrong with this regular expression

I'm doing some experiments with regular expressions and I don't know why the regex don't match. 我正在使用正则表达式进行一些实验,但我不知道为什么正则表达式不匹配。

string line is one line from a file. 字符串行是文件中的一行。 A line which should match is this 应该匹配的线是这个

["boxusers:settings/user[boxuser11]/name"] = "username", 

The number of the boxuser and the value could be different, so I tried to find a regular expression boxuser的数量和值可以不同,所以我尝试找到一个正则表达式

My code is this: 我的代码是这样的:

string user;
string patternUser = "[\"boxusers:settings/user[boxuser\\d{2,}]/name\"] = \"";
if (Regex.Match(line,patternUser).Success)
   user = Regex.Replace(Regex.Replace(line, patternUser, String.Empty), ",*", String.Empty);

So I think \\d{2,0} should be a number with two digits and the rest is just the same. 所以我认为\\ d {2,0}应该是一个带有两位数字的数字,其余的都一样。 But the regex just don't match. 但是正则表达式不匹配。

What's going wrong? 怎么了

Square brackets have a special significance in regular expressions. 方括号在正则表达式中具有特殊意义。 You need to escape them with a backslash. 您需要使用反斜杠将其转义。

var line = @"[""boxusers:settings/user[boxuser11]/name""] = ""username"", ";
string patternUser = @"\[""boxusers:settings/user\[boxuser\d{2,}\]/name""\] = """;
Console.WriteLine(Regex.Match(line, patternUser).Success);

If you don't want to use verbatim strings, you'll need to use two backslashes to escape each regex metacharacter (the first to escape the second). 如果您不想使用逐字字符串,则需要使用两个反斜杠来转义每个正则表达式元字符(第一个转义第二个字符)。

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

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