[英]Why does my regular expression pattern in C# return an empty string?
I have aa string that's formatted such \\\\\\State\\city"
.我有一个格式为\\\\\\State\\city"
字符串。
I want to return only the State portion and then only the city portion into respective variables.我只想将 State 部分返回,然后只将 city 部分返回到相应的变量中。
I tried using a pattern of ^\\\\\\\\[a-zA-Z]\\
to return the state portion and then a pattern of ^\\\\[a-zA-Z]
for the city portion.我尝试使用^\\\\\\\\[a-zA-Z]\\
返回州部分,然后使用^\\\\[a-zA-Z]
模式返回城市部分。 The results are always an empty string.结果总是一个空字符串。
state = Regex.Match("\\\Washington\\Seattle","^\\\\[a-zA-Z]\"].ToString();
Backslash serves as an escape character.反斜杠用作转义字符。 For every single ( \\
) backslash you need two backslashes ( \\\\
).对于每一个( \\
)反斜杠,你需要两个反斜杠( \\\\
)。
Also you do not need the beginning of line anchor ^
on your second regular expression example because that part is obviously not at the beginning of the string.此外,您在第二个正则表达式示例中不需要行锚^
的开头,因为该部分显然不在字符串的开头。 Below is an example of how you could do this.下面是如何执行此操作的示例。
String s = @"\\Washington\Seattle";
Match m = Regex.Match(s, @"(?i)^\\\\([a-z]+)\\([a-z]+)");
if (m.Success) {
String state = m.Groups[1].Value;
String city = m.Groups[2].Value;
Console.WriteLine("{0}, {1}", city, state); // => "Seattle, Washington"
}
Try this non-RegEx answer:试试这个非正则表达式答案:
string data = @"\\Washington\Seattle";
string state = data.Trim('\\').Split('\\')[0];
string city = data.Trim('\\').Split('\\')[1];
Console.WriteLine("{0}, {1}", city, state);
This is trimming the double backslashes, then splitting at the first backslash.这是修剪双反斜杠,然后在第一个反斜杠处拆分。
You need to escape backslashes in regex.您需要在正则表达式中转义反斜杠。 So anywhere that you would have a single \\
, instead have \\\\
所以任何地方你都会有一个\\
,而不是有\\\\
Also [a-zA-Z]
will only match once. [a-zA-Z]
也只会匹配一次。 Use a +
to match once or more使用+
匹配一次或多次
So that would make your state regex:所以这将使您的状态正则表达式:
^\\\\\\\\[a-zA-Z]+\\\\
Additionally, backslashes in strings in C# also need to be escaped.此外,C# 中字符串中的反斜杠也需要转义。 So either double up again, or use the @
character:所以要么再次加倍,要么使用@
字符:
state = Regex.Match(@"\\Washington\Seattle",@"^\\\\[a-zA-Z]+\\").ToString();
You only allow one character to stand between your backslashes.你只允许一个字符站在你的反斜杠之间。 what you actually want is [a-zA-Z]*
with the asterisk.你真正想要的是带星号的[a-zA-Z]*
。
Consider the following code to match State and City...考虑以下代码来匹配州和城市...
var state = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\).*(?=\\)");
var city = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\.*?\\).*");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.