Reputation: 1161
My very weak point is regular expressions and I hope someone can help me. I have a string:
string comment = myOrder[Original Tel Number: Some string that can be any size basically\nHome: 94036\nPostal Code: B4]
Now I am trying to break up this string like this:
var match = Regex.Match( comment, @"Original Tel Number:\s(\w+)\s*\nHome:\s(\w+)\s*\nPostal Code:\s(\w+)" );
if ( match.Success )
{
inputOrder.BaseHomeTel = match.Groups[1].Value;
inputOrder.Home = match.Groups[2].Value;
inputOrder.PostalCode = match.Groups[3].Value;
}
But it just never seems to match, what am I doing wrong here.
Upvotes: 0
Views: 128
Reputation: 227
This will match your string:
@"Original Tel Number:(.*?)\nHome:(.*?)\nPostal Code:(.*)"
But those \n:s are linebreaks, I assume, which are matched by either \n, \r, or \r\n depending on OS. So try this instead:
@"Original Tel Number:(.*?)(?\n|\r|\r\n)Home:(.*?)(?\n|\r|\r\n)Postal Code:(.*)"
...Or you can fiddle around with RegexOptions.MultiLine and use $ to match linebreaks.
Upvotes: 0
Reputation: 10427
Try this one:
@"Original Tel Number:\s*([\w\s]+?)\s*Home:\s*([\w\s]+?)\s*Postal Code:\s*([\w\s]+)"
Upvotes: 0
Reputation: 336198
Tel Number:\s(\w+)\s*\nHome:
matches Tel Number:
, followed by one whitespace character, followed by one alphanumeric word, followed by optional whitespace and a newline, then by Home:
.
Your string contains several words here, which is why the regex fails.
You probably want to allow multiple words:
@"Original Tel Number:((?:\s+\w+)+)\s*\nHome:\s(\w+)\s*\nPostal Code:\s(\w+)"
Upvotes: 1