Csharp/C Sharp/Development Class/Regular Expression — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:45, 26 мая 2010
Содержание
- 1 ((an)|(in)|(on))
- 2 Define groups "ing", "in", "n"
- 3 Gr(a|e)y
- 4 HTML Parser
- 5 IP address
- 6 Leading space
- 7 Multiple different delimiters
- 8 Multiple spaces, using \" \"
- 9 Multiple spaces, using \"[\\s]+\"
- 10 Position and index
- 11 Proper case match
- 12 Regex and letter case
- 13 Single space split
- 14 Single spaces, using ()
- 15 Single spaces, using new Regex("( )")
- 16 Use regular expression to replace chars
- 17 Use regular expression to replace first 3 digits
- 18 Use regular to replace strings
- 19 Use regular to replace word
- 20 Use regular to split string
- 21 Use regular to verify a date
- 22 Use | to combine different case
- 23 Validate address
- 24 Validate city name
- 25 Validate first name and last name
- 26 Validate Phone Number
- 27 Validate ZIP code
((an)|(in)|(on))
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);
}
}
}
Define groups "ing", "in", "n"
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);
}
}
}
Gr(a|e)y
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);
}
}
}
HTML Parser
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");
}
}
IP address
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]);
}
}
Leading space
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);
}
}
Multiple different delimiters
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);
}
}
}
Multiple spaces, using \" \"
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);
}
}
}
Multiple spaces, using \"[\\s]+\"
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);
}
}
}
Position and index
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);
}
}
}
Proper case match
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);
}
}
Regex and letter case
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);
}
}
}
Single space split
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);
}
}
}
Single spaces, using ()
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);
}
}
}
Single spaces, using new Regex("( )")
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);
}
}
}
Use regular expression to replace chars
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 );
}
}
Use regular expression to replace first 3 digits
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 ) );
}
}
Use regular to replace strings
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 );
}
}
Use regular to replace word
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" ) );
}
}
Use regular to split string
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 + "\", ");
}
}
Use regular to verify a date
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 );
}
}
Use | to combine different case
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);
}
}
}
Validate address
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");
}
}
}
Validate city name
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");
}
}
}
Validate first name and last name
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");
}
}
}
Validate Phone Number
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");
}
}
}
Validate ZIP code
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");
}
}
}