I’m horrible with regex but i’m trying to figure out how an import function works and i came across this regex pattern. Maybe one of you can help me understand how it works.
string pattern = @"^""(?<code>.*)"",""(?<last_name>.*)"",""(?<first_name>.*)"",""(?<address>.*)"",""(?<city>.*)"",""(?<state>.*)"",""(?<zip>.*)""$";
Regex re = new Regex(pattern);
Match ma = re.Match(_sReader.ReadLine().Trim());
Thanks
It looks like it’s trying to split a comma delimited string (with the fields having quotes around them) into separate fields with named groups. The
(?<name>...)syntax captures the fields into named groups. The^indicates the match has to begin at the start of the string and the$is the end of string anchor. The.*in each group says to capture everything (any character, zero or more times) that occur between the double quotes.Basically, it should parse the input CSV string into an array of strings that you can refer to by group name. You can reference the captured groups using
ma.Groups[x]where x is an integer or you can use the group name. For example,ma.Groups["code"].