As an analysis technology, regular expressions can be used in many places, and most basic expressions may be used by everyone. Here, we will explain the regular expression through a series of simple examples. How to analyze the required data for a given address, for example, the following URL, the basic idea of analyzing each query string is: 1 first get it? The following part, 2, then split according to & and =, and get first? The following part matches the regular expression of the query string :\? (? <Querystring> ([^ &] + &?) +), The regular expression for removing the naming part is :\? ([^ &] + &?) + Matched '? Word = test & tn = sitehao123 & ie = UTF-8 \? ([^ &] + &?) + Description :\? Indicates already? Because? The regular expression has special meanings, so a slash \ escape is required. [^ &] + Indicates that the matching is not any or multiple characters &? Indicates that & appears once or does not appear \? ([^ &] + &?) + The overall meaning is that 1 matches? The first 2 2.1 matches are not & multiple characters 2.2 matches & one or no 2.3 repeats 2.1, 2.2 times or multiple times 3 ([^ &] + &?) +) If some matched characters are named querystring, the regular expression is changed :\? (? <Querystring> ([^ &] + &?) +) 2. Then, the regular expression of the query string based on & and = is :((? <Key> [^ & =] +) = (? <Value> [^ & =] +) +, removes the regular expression of the naming part as :( ([^ & =] +) = ([^ & =] + )) + [^ & =] + indicates that the match is not any or multiple characters ([^ & =] +) = ([^ & =] + )) + The overall meaning is that 1 matching is not any or multiple characters, 2 matching equal signs = 3 matching is not any or multiple characters, 4 repeating more than 1, 2, 3. Name the matching character 1 as the key, and the matching character 3 as the value. Then, the regular expression is changed ((? <Key> [^ & =] +) = (? <Value> [^ & =] +) + the test code is as follows:
private static void Test() { string url = "http://www.baidu.com/s?word=test&tn=sitehao123&ie=utf-8"; Regex reg = new Regex(@"\?(?<querystring>([^&]+&?)+)"); Match m = reg.Match(url); string querystring = m.Groups["querystring"].Value; Regex reg2 = new Regex(@"((?<key>[^&=]+)=(?<value>[^&=]+))+"); Dictionary<string, string> querystringKeyValue = new Dictionary<string, string>(); foreach (Match item in reg2.Matches(querystring)) { querystringKeyValue.Add(item.Groups["key"].Value, item.Groups["value"].Value); } }