Csharp/C Sharp/Development Class/Regular Expression

Материал из .Net Framework эксперт
Версия от 14:45, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

((an)|(in)|(on))

<source lang="csharp"> using System; using System.Text.RegularExpressions; public class MainClass {

   public static void Main() {
       Regex p = new Regex("((an)|(in)|(on))");
       MatchCollection mn = p.Matches("King, Kong Kang");
       for (int i = 0; i < mn.Count; i++) {
           Console.WriteLine("Found "{0}" at position {1}",mn[i].Value, mn[i].Index);
       }
   }

}

</source>


Define groups "ing", "in", "n"

<source lang="csharp">

using System; using System.Text.RegularExpressions; class GroupingApp {

   static void Main(string[] args) {
       Regex r = new Regex("(i(n))g");
       Match m = r.Match("Matching");
       GroupCollection gc = m.Groups;
       Console.WriteLine("Found {0} Groups", gc.Count);
       for (int i = 0; i < gc.Count; i++) {
           Group g = gc[i];
           Console.WriteLine("Found "{0}" at position {1}",g.Value, g.Index);
       }
   }

}

</source>


Gr(a|e)y

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       Regex n = new Regex("Gr(a|e)y");
       MatchCollection mp = n.Matches("Green, Grey, Granite, Gray");
       for (int i = 0; i < mp.Count; i++) {
           Console.WriteLine("Found "{0}" at position {1}",mp[i].Value, mp[i].Index);
       }
   }

}

</source>


HTML Parser

<source lang="csharp"> using System; using System.Text.RegularExpressions; using System.IO; using System.Text; public class HTMLParser {

   public static void Main(String[] args) {
       FileInfo MyFile = new FileInfo(args[0].ToString());
       if (MyFile.Exists) {
           StreamReader sr = MyFile.OpenText();
           string text = sr.ReadToEnd();
           sr.Close();
           string pattern = @"<a\shref\S*/a>";
           MatchCollection patternMatches = Regex.Matches(text, pattern,
             RegexOptions.IgnoreCase);
           foreach (Match nextMatch in patternMatches) {
               Console.WriteLine(nextMatch.ToString());
           }
       } else
           Console.WriteLine("The input file does not exist");
   }

}

</source>


IP address

<source lang="csharp"> using System; using System.Text.RegularExpressions;

class RXassemblyApp {

   static void Main(string[] args) {
       string s = "123.45.67.89";
       string e =
           @"([01]?\d\d?|2[0-4]\d|25[0-5])\." +
           @"([01]?\d\d?|2[0-4]\d|25[0-5])\." +
           @"([01]?\d\d?|2[0-4]\d|25[0-5])\." +
           @"([01]?\d\d?|2[0-4]\d|25[0-5])";
       Match m = Regex.Match(s, e);
       Console.WriteLine("IP Address: {0}", m);
       for (int i = 1; i < m.Groups.Count; i++)
           Console.WriteLine(
               "\tGroup{0}={1}", i, m.Groups[i]);
   }

}

</source>


Leading space

<source lang="csharp"> using System; using System.Text.RegularExpressions;

class RXmodifyingApp {

   static void Main(string[] args) {
       string s = "     leading";
       string e = @"^\s+";
       Regex rx = new Regex(e);
       string r = rx.Replace(s, "");
       Console.WriteLine("Strip leading space: {0}", r);
   }

}

</source>


Multiple different delimiters

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string t = "Once,Upon:A/Time\\In\"America";
       Regex q = new Regex(@" |,|:|/|\\|\"");
       foreach (string ss in q.Split(t)) {
           Console.WriteLine(ss);
       }
   }

}

</source>


Multiple spaces, using \" \"

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string u = "Once   Upon A Time In   America";
       Regex p = new Regex(" ");
       foreach (string ss in p.Split(u)) {
           Console.WriteLine(ss);
       }
   }

}

</source>


Multiple spaces, using \"[\\s]+\"

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string v = "Once   Upon A Time In   America";
       Regex o = new Regex(@"[\s]+");
       foreach (string ss in o.Split(v)) {
           Console.WriteLine(ss);
       }
   }

}

</source>


Position and index

<source lang="csharp"> using System; using System.Text.RegularExpressions;

class MatchingApp {

   static void Main(string[] args) {
       Regex r = new Regex("in");
       Match m = r.Match("Matching");
       if (m.Success) {
           Console.WriteLine("Found "{0}" at position {1}",m.Value, m.Index);
       }
   }

}

</source>


Proper case match

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class RXProperCaseApp {

   static void Main(string[] args) {
       string s = "the qUEEn wAs in HER parLOr";
       s = s.ToLower();
       string e = @"\w+|\W+";
       string sProper = "";
       foreach (Match m in Regex.Matches(s, e)) {
           sProper += char.ToUpper(m.Value[0])
               + m.Value.Substring(1, m.Length - 1);
       }
       Console.WriteLine("ProperCase:\t{0}", sProper);
   }

}

</source>


Regex and letter case

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       Regex q = new Regex(" in ");
       MatchCollection mm = q.Matches("IN at in or");
       for (int i = 0; i < mm.Count; i++) {
           Console.WriteLine("Found "{0}" at position {1}",mm[i].Value, mm[i].Index);
       }
   }

}

</source>


Single space split

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string u = "Once   Upon A Time In   America";
       Regex p = new Regex(" ");
       foreach (string ss in p.Split(u)) {
           if (ss.Length > 0)
               Console.WriteLine(ss);
       }
   }

}

</source>


Single spaces, using ()

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string x = "Once Upon A Time In America";
       Regex m = new Regex("( )");
       foreach (string ss in m.Split(x)) {
           Console.WriteLine(ss);
       }
   }

}

</source>


Single spaces, using new Regex("( )")

<source lang="csharp"> using System; using System.Text.RegularExpressions;

public class MainClass {

   public static void Main() {
       string x = "Once Upon A Time In America";
       Regex m = new Regex("( )");
       foreach (string ss in m.Split(x)) {
           Console.WriteLine(ss);
       }
   }

}

</source>


Use regular expression to replace chars

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string testString1 = " stars *****";
     Regex testRegex1 = new Regex( @"\d" );
     Console.WriteLine( "Original string: " + testString1 );
     testString1 = Regex.Replace( testString1, @"\*", "^" );
     Console.WriteLine( "^ substituted for *: " + testString1 );
     
  }

}


      </source>


Use regular expression to replace first 3 digits

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
     Regex testRegex1 = new Regex( @"\d" );
     Console.WriteLine( "Original string: " + testString1 );
     Console.WriteLine( "Replace first 3 digits by \"digit\": " + testRegex1.Replace( testString1, "digit", 3 ) );
  }

}

      </source>


Use regular to replace strings

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string testString1 = " stars *****";
     Regex testRegex1 = new Regex( @"\d" );
     Console.WriteLine( "Original string: " + testString1 );
     testString1 = Regex.Replace( testString1, "stars", "carets" );
     Console.WriteLine( "\"carets\" substituted for \"stars\": " + testString1 );
     
  }

}

      </source>


Use regular to replace word

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string testString1 = "a b c stars *****";
     Regex testRegex1 = new Regex( @"\d" );
     Console.WriteLine( "Original string: " + testString1 );
     Console.WriteLine( "Every word replaced by \"word\": " + Regex.Replace( testString1, @"\w+", "word" ) );
     
  }

}

      </source>


Use regular to split string

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
     Regex testRegex1 = new Regex( @"\d" );
     Console.WriteLine( "Original string: " + testString1 );
     String[] result = Regex.Split( testString1, @",\s" );
     foreach ( string resultString in result )
        Console.WriteLine("\"" + resultString + "\", ");
  }

}

      </source>


Use regular to verify a date

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexMatches {

  public static void Main()
  {
     Regex expression = new Regex( @"J.*\d[0-35-9]-\d\d-\d\d" );
     string string1 = "Jane"s Birthday is 05-12-75\n" +
        "Jave"s Birthday is 11-04-78\n" +
        "John"s Birthday is 04-28-73\n" +
        "Joe"s Birthday is 12-17-77";
     foreach ( Match myMatch in expression.Matches( string1 ) )
        Console.WriteLine( myMatch );
  }

}

      </source>


Use | to combine different case

<source lang="csharp"> using System; using System.Text.RegularExpressions;

class RXOptionsApp {

   static void Main(string[] args) {
       Regex r = new Regex("in|In|IN|iN");
       string s = "The KING Was In His Counting House";
       MatchCollection mc = r.Matches(s);
       for (int i = 0; i < mc.Count; i++) {
           Console.WriteLine("Found "{0}" at position {1}",mc[i].Value, mc[i].Index);
       }
   }

}

</source>


Validate address

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string text = "124 street";
     if ( !Regex.Match( text, @"^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$" ).Success ) {
        Console.WriteLine( "Invalid address");
     } 
  }

}


      </source>


Validate city name

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string text = "124 street";
     if ( !Regex.Match(text,@"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$" ).Success )
     {
        Console.WriteLine( "Invalid city");
     } 
  }

}

      </source>


Validate first name and last name

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string text = "Name";
     if ( !Regex.Match(text,"^[A-Z][a-zA-Z]*$" ).Success )
     {
        Console.WriteLine( "Invalid last name");
     }
  }

}


      </source>


Validate Phone Number

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string text = "124";
     if ( !Regex.Match(text,@"^[1-9]\d{2}-[1-9]\d{2}-\d{4}$" ).Success )
     {
        Console.WriteLine( "Invalid phone number");
     }   
  }

}

      </source>


Validate ZIP code

<source lang="csharp"> using System; using System.Text.RegularExpressions; class RegexSubstitution {

  public static void Main()
  {
     string text = "124";
     if ( !Regex.Match( text, @"^\d{5}$" ).Success )
     {
        Console.WriteLine( "Invalid zip code");
     }   
  }

}

      </source>