1. Split string
1.1 The following is a demo of sentence splitting:
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Program { Public static void Main (string [] args) { Console. WriteLine ("Enter the string to be split and press Enter to confirm. "); String input = Console. ReadLine (); String pattern = @ ". |, |: |; |. |, |: | ;"; String [] rs = Regex. Split (input, pattern ); Console. WriteLine ("The split clause is :"); Foreach (string s in rs) { Console. WriteLine (s ); } Console. ReadKey (true ); } } }
|
1.2 Split HTML tags
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Program { Public static void Main (string [] args) { String input = "<B> This is a </B> <B> lonely day. </B> <B> sadly </B> <B> rain. </B> "; String pattern = "<[^>] *> "; Regex r = new Regex (pattern ); String [] rs = r. Split (input ); Console. WriteLine ("The split clause is :"); Foreach (string s in rs) { Console. WriteLine (s ); } Console. ReadKey (true ); } } } |
--------------------------------------------------------------------------------
2. Query strings
The Regex class provides three methods for string query and matching, Match, Matchs, and IsMatch.
2.1 Match searches for the regular expression specified in the Regex constructor in the specified input string and returns a Match object. If the Success attribute of the Match object is true, a matched string exists, as described in the previous blog, NextMatch can be used for the next match.
The following example finds all the URLs with quotation marks in the HTML fragment.
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Test { Static void PrintURL (string s) { String pattern = "href \ s * = \ s *" [^ "] *" "; Match m = Regex. Match (s, pattern ); While (m. Success) { Console. WriteLine (m. Value ); M = m. NextMatch (); } } Public static void Main () { PrintURL ("href =" http: \ www.baidu.com "href =" http: \ www.soso.com ""); Console. ReadKey (); } } } |
--------------------------------------------------------------------------------
2.2 The above example can also simplify the return of a MatchCollection set and use foreach traversal:
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Test { Static void PrintURL (string s) { String pattern = "href \ s * = \ s *" [^ "] *" "; MatchCollection m = Regex. Matches (s, pattern ); Foreach (Match str in m) { Console. WriteLine (str ); } } Public static void Main () { PrintURL ("href =" http: \ www.baidu.com "href =" http: \ www.soso.com ""); Console. ReadKey (); } } } |
If we only want to know the referenced address, we can use the Groups attribute of the capture group and Match class. For example:
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Test { Static void PrintURL (string s) { String pattern = "href \ s * = \ s *" ([^ "] *)" "; MatchCollection m = Regex. Matches (s, pattern ); Foreach (Match str in m) { Console. WriteLine (str. Groups [0]); } } Public static void Main () { PrintURL ("href =" http: \ www.111cn.net "href =" http: \ www.soso.com ""); Console. ReadKey (); } } } |
--------------------------------------------------------------------------------
2.3.1 IsMatch indicates whether matching items are found in the regular expression and then the string.
Find whether a character contains <a>
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Program { Public static void Main (string [] args) { Regex r = new Regex ("<a [^>] *>", RegexOptions. IgnoreCase ); If (r. IsMatch ("<a href =" http://www.baidu.com/"> Link </a> ")) Console. WriteLine ("include <a> tag "); Else Console. WriteLine ("does not contain <a> tags "); Console. ReadKey (true ); } } }
|
2.3.2 used to verify the input of 16 numbers
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Program { Public static void Main (string [] args) { Regex r = new Regex (@ "^ d {4}-d {4}-d {4}-d {4} $ "); If (r. IsMatch ("1216-2593-3395-2612 ")) Console. WriteLine ("passed "); Else Console. WriteLine ("failed "); Console. ReadKey (true ); } } } |
--------------------------------------------------------------------------------
3. Replace string
The Replace method of the Regex class is used to Replace strings. The following code replaces "China" in the input string with "China ".
The code is as follows: |
Copy code |
Using System; Using System. Text. RegularExpressions; Namespace RegexSplit { Class Test { Static void EtoC (string s) { Console. WriteLine ("source string: n {0}", s ); Console. WriteLine ("replaced :"); Console. WriteLine (Regex. Replace (s, "China", "China ")); } Public static void Main () { EtoC ("China, my motherland, China, China! "); Console. ReadKey (); } } } |
For example, the following function demonstrates how to use a regular expression to verify Zip code:
The code is as follows: |
Copy code |
Private void ValidateZipButton_Click (object sender, System. EventArgs e) { String ZipRegex = @ "^ d {5} $ "; If (Regex. IsMatch (ZipTextBox. Text, ZipRegex )) { ResultLabel. Text = "ZIP is valid! "; } Else { ResultLabel. Text = "ZIP is invalid! "; } }
|
Similarly, you can use the static Replace () method to Replace a match with a specific string, as shown below:
String newText = Regex. Replace (inputString, pattern, replacementText );
Finally, you can use the following code to traverse the matching set of input strings:
The code is as follows: |
Copy code |
Private void MatchButton_Click (object sender, System. EventArgs e) { MatchCollection matches = Regex. Matches (SearchStringTextBox. Text, MatchExpressionTextBox. Text ); MatchCountLabel. Text = matches. Count. ToString (); MatchesLabel. Text = ""; Foreach (Match match in matches) { MatchesLabel. Text + = "Found" + match. ToString () +" Position "+ match. Index +". <br> "; } }
|
Generally, you need to instantiate an instance of the Regex class when you need to specify a method other than the default method. Especially when setting options. For example, if you want to create a Regex instance that ignores case-insensitive and mode-blank areas and then retrieve a set that matches the expression, use the following code:
The code is as follows: |
Copy code |
Regex re = new Regex (pattern, RegexOptions. IgnoreCase | RegexOptions. IgnorePatternWhitespace ); MatchCollection mc = re. Matches (inputString ); |
Http url verification
The code is as follows: |
Copy code |
Public Function IsValidUrl (ByVal Url As String) As Boolean Dim strRegex As String = "^ (https? ://)"_ &"? ([0-9a-z _!~ * '(). & =+ $ %-] + :)? [0-9a-z _!~ * '(). & =+ $ %-] + @)? "_ & "([0-9] {1, 3}.) {3} [0-9] {1, 3 }"_ & "| "_ & "([0-9a-z _!~ * '()-] + .)*"_ & "([0-9a-z] [0-9a-z-] {0, 61 })? [0-9a-z]. "_ & "[A-z] {2, 6 })"_ & "(: [0-9] {1, 4 })? "_ &"((/?) | "_ & "(/[0-9a-z _!~ *'().;? : @ & =+ $, % #-] +) + /?) $" Dim re As RegularExpressions. Regex = New RegularExpressions. Regex (strRegex) MessageBox. Show ("IP:" & Net. IPAddress. TryParse (Url, Nothing )) If re. IsMatch (Url) Then Return True Else Return False End If End Function |