c# - How to allow space in regex? -
i trying value after new : in double quote. can retrieve value fine when there no space in listname. if put space between list name (eg. newfinancial history:\"xyz\"), throws error below:
parsing "newfinancial history:"(?[^"]*)"" - invalid group name: group names must begin word character.
it throws error @ below line var matches = regex.matches(contents, regex, regexoptions.singleline);
below code.
string contents = " testing newfinancial history:\"xyz\" "; var keys = regex.matches(contents, @"new(.+?):", regexoptions.singleline | regexoptions.ignorepatternwhitespace).oftype<match>().select(m => m.groups[0].value.trim().replace(":", "")).distinct().toarray(); foreach (string key in keys) { list<string> valuelist = new list<string>(); string listnamekey = key; string regex = "" + listnamekey + ":" + "\"(?<" + listnamekey + ">[^\"]*)\""; var matches = regex.matches(contents, regex, regexoptions.singleline); foreach (match match in matches) { if (match.success) { string value = match.groups[key].value; valuelist.add(value); } } }
i don't see why use "key" name of group.
the problem have group name not contain spaces, create anonymous group.
string contents = " testing newfinancial history:\"xyz\" "; var keys = regex.matches(contents, @"new(.+?):", regexoptions.singleline | regexoptions.ignorepatternwhitespace).oftype<match>().select(m => m.groups[0].value.trim().replace(":", "")).distinct().toarray(); foreach (string key in keys) { list<string> valuelist = new list<string>(); string listnamekey = key; string regex = "" + listnamekey + ":" + "\"([^\"]*)\""; //create anonymous capture group var matches = regex.matches(contents, regex, regexoptions.singleline); foreach (match match in matches) { if (match.success) { string value = match.groups[0].value; //get first group valuelist.add(value); } } }
Comments
Post a Comment