using System.Text.RegularExpressions
Roman Numbers
string p1 = "^m*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])";
string t1 = "vii"; Match m1 = Regex.Match(t1, p1);
Swapping First Two Words
string t2 = "the quick brown fox";
string p2 = @"(\S+)(\s+)(\S+)";
Regex x2 = new Regex(p2);
string r2 = x2.Replace(t2, "$3$2$1", 1);
Keyword = Value
string t3 = "myval = 3";
string p3 = @"(\w+)\s*=\s*(.*)\s*";;
Match m3 = Regex.Match(t3, p3);
Line of at Least 80 Characters
string t4 = "********************"
+ "******************************"
+ "******************************";
string p4 = ".{80,}";
Match m4 = Regex.Match(t4, p4);
MM/DD/YY HH:MM:SS
string t5 = "01/01/01 16:10:01";
string p5 = @"(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)";
Match m5 = Regex.Match(t5, p5);
Changing Directories (for Windows)
string t6 = @"C:\Documents and Settings\user1\Desktop\";
string r6 = Regex.Replace(t6, @\\user1\\, @\\user2\\);
Expanding (%nn) Hex Escapes
string t7 = "%41"; // capital A
string p7 = "%([0-9A-Fa-f][0-9A-Fa-f])";
// uses a MatchEvaluator delegate
string r7 = Regex.Replace(t7, p7, HexConvert);
Deleting C Comments (Imperfectly)
string t8 = @"
/*
* this is an old cstyle comment block
*/
";
string p8 = @"
/\* # match the opening delimiter
.*? # match a minimal numer of chracters
\*/ # match the closing delimiter
";
string r8 = Regex.Replace(t8, p8, "", "xs");
Removing Leading and Trailing Whitespace
string t9a = " leading";
string p9a = @"^\s+";
string r9a = Regex.Replace(t9a, p9a, "");
string t9b = "trailing ";
string p9b = @"\s+";
string r9b = Regex.Replace(t9b, p9b, "");
Turning '\' Followed by 'n' Into a Real Newline
string t10 = @"\ntest\n";
string r10 = Regex.Replace(t10, @"\\n", "\n");
IP Address
string t11 = "55.54.53.52";
string p11 = "^" +
@"([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 m11 = Regex.Match(t11, p11);
Removing Leading Path from Filename
string t12 = @"c:\file.txt";
string p12 = @"^.*\\";
string r12 = Regex.Replace(t12, p12, "");
Joining Lines in Multiline Strings
string t13 = @"this is
a split line";
string p13 = @"\s*\r?\n\s*";
string r13 = Regex.Replace(t13, p13, " ");
Extracting All Numbers from a String
string t14 = @"
test 1
test 2.3
test 47
";
string p14 = @"(\d+\.?\d*|\.\d+)";
MatchCollection mc14 = Regex.Matches(t14, p14);
No comments:
Post a Comment