|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace IDontLikeRegex
{
public static class StringExt
{
public static bool Like(this string item, string searchPattern)
{
var regex = GetRegex("^" + searchPattern);
return regex.IsMatch(item);
}
public static string Search(this string item, string searchPattern)
{
var match = GetRegex(searchPattern).Match(item);
if (match.Success)
{
return item.Substring(match.Index, match.Length);
}
return null;
}
public static List<string> Extract(this string item, string searchPattern)
{
var result = item.Search(searchPattern);
if (!string.IsNullOrWhiteSpace(result))
{
var splitted = searchPattern.Split(new[] { '?', '%', '*', '#' }, StringSplitOptions.RemoveEmptyEntries);
var temp = result;
var final = new List<string>();
foreach(var x in splitted)
{
var pos = temp.IndexOf(x);
if (pos > 0)
{
final.Add(temp.Substring(0, pos));
temp = temp.Substring(pos);
}
temp = temp.Substring(x.Length);
}
if (temp.Length > 0) final.Add(temp);
return final;
}
return null;
}
// private method which accepts the simplified pattern and transform it into a valid .net regex pattern:
// it escapes standard regex syntax reserved characters
// and transforms the simplified syntax into the native Regex one
static Regex GetRegex(string searchPattern)
{
return new Regex(searchPattern
.Replace("\\", "\\\\")
.Replace(".", "\\.")
.Replace("{", "\\{")
.Replace("}", "\\}")
.Replace("[", "\\[")
.Replace("]", "\\]")
.Replace("+", "\\+")
.Replace("$", "\\$")
.Replace(" ", "\\s")
.Replace("#", "[0-9]")
.Replace("?", ".")
.Replace("*", "\\w*")
.Replace("%", ".*")
, RegexOptions.IgnoreCase);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.