Consider the following code to match State and City...
var state = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\).*(?=\\)");
var city = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\.*?\\).*");
Question
I have a a string that's formatted such \\\State\city"
.
I want to return only the State portion and then only the city portion into respective variables.
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. The results are always an empty string.
state = Regex.Match("\\\Washington\\Seattle","^\\\\[a-zA-Z]\"].ToString();
La solution 3
Consider the following code to match State and City...
var state = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\).*(?=\\)");
var city = Regex.Match(@"\\Washington\Seattle", @"(?<=\\\\.*?\\).*");
Autres conseils
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. 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. 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.