C# Source Code: Re: Re: Re: Using RegEx to create a
[
Home
|
Contents
|
Search
|
Reply
|
Previous
|
Next
]
C# Source Code
Re: Re: Re: Using RegEx to create a
By:
stefan
Email (spam proof):
Email the originator of this post
Date:
Wednesday, December 22, 2004
Hits:
1004
Category:
General/Framework
Article:
hi andrew! i post u the complete code - the main trick is to convert a LIKE pattern to a proper REGEX pattern - this is done by "LikePatternToRegex(string pattern) " performancewise its best to reuse the regex with a given pattern - this is done through "GetRegexFromPattern (string pattern)". you can assign this regex to a regex var and execute the pattern several time. if you really like to compare a pattern only once use Exec (string text, string pattern...) btw, the thing with "Add beginn and end blocks" for the regex helped me alot. i never understood how to match the WHOLE string only. stefan ------c# CODE------ using System; using System.Text.RegularExpressions; using System.Diagnostics; namespace Helper.Text { public class Comparer { ///
/// Converts a LIKE (VB) Pattern to a corresponding RegEx Pattern ///
///
///
public static string LikePatternToRegex (string pattern) { //Escape all chars System.Text.StringBuilder regPattern=new System.Text.StringBuilder(Regex.Escape(pattern)); //Replace the LIKE chars with the required regular expressions sequences regPattern= regPattern.Replace (Regex.Escape("*"), ".*"); regPattern= regPattern.Replace (Regex.Escape("?"), @"."); regPattern= regPattern.Replace (Regex.Escape("#"), @"[0-9]"); regPattern= regPattern.Replace (Regex.Escape("[!"), @"[!"); regPattern= regPattern.Replace (Regex.Escape("["), @"["); regPattern= regPattern.Replace (Regex.Escape("]"),@"]"); //Add begin and end blocks - important for "whole string" matching regPattern.Insert(0, "^"); regPattern.Append("$"); return regPattern.ToString(); } public static Regex GetRegexFromPattern (string pattern) { return new Regex (LikePatternToRegex(pattern)); } ///
/// Like mit Regex gelöst ///
///
///
///
///
Wenn true dann wird die Regex gespeichert und für dieses pattern wiederverwendet, grosser performancegewinn wenn regex öfter verwendet wird ///
public static bool Exec(string text, string pattern, bool ignoreCase) { //Von: http://www.vbusers.com/codecsharp/codeget.asp?ThreadID=25&PostID=1&NumReplies=2 if(text != null && pattern != null && pattern.Length > 0) { if(pattern == null || text == null) { return false; } if(pattern == "*" || pattern == "*.*") { return true; } string regPattern=LikePatternToRegex(pattern); if(ignoreCase == false) { return Regex.IsMatch(text, regPattern.ToString()); } else { return Regex.IsMatch(text, regPattern.ToString(), RegexOptions.IgnoreCase); } } return false; } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet