Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- public class MyClass
- {
- public static void RunSnippet()
- {
- string text = "*or*";
- string[] list = new String[]{"Hello World", "Hortel", "Wazzup"};
- Wildcard wildcard = new Wildcard(text, RegexOptions.IgnoreCase);
- foreach(var item in list)
- {
- if(wildcard.IsMatch(item))
- {
- WL(item);
- }
- }
- }
- #region Helper methods
- public static void Main()
- {
- try
- {
- RunSnippet();
- }
- catch (Exception e)
- {
- string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
- Console.WriteLine(error);
- }
- finally
- {
- Console.Write("Press any key to continue...");
- Console.ReadKey();
- }
- }
- private static void WL(object text, params object[] args)
- {
- Console.WriteLine(text.ToString(), args);
- }
- private static void RL()
- {
- Console.ReadLine();
- }
- private static void Break()
- {
- System.Diagnostics.Debugger.Break();
- }
- #endregion
- }
- /// <summary>
- /// Represents a wildcard running on the
- /// <see cref="System.Text.RegularExpressions"/> engine.
- /// </summary>
- public class Wildcard : Regex
- {
- /// <summary>
- /// Initializes a wildcard with the given search pattern.
- /// </summary>
- /// <param name="pattern">The wildcard pattern to match.</param>
- public Wildcard(string pattern)
- : base(WildcardToRegex(pattern))
- {
- }
- /// <summary>
- /// Initializes a wildcard with the given search pattern and options.
- /// </summary>
- /// <param name="pattern">The wildcard pattern to match.</param>
- /// <param name="options">A combination of one or more
- /// <see cref="System.Text.RegexOptions"/>.</param>
- public Wildcard(string pattern, RegexOptions options)
- : base(WildcardToRegex(pattern), options)
- {
- }
- /// <summary>
- /// Converts a wildcard to a regex.
- /// </summary>
- /// <param name="pattern">The wildcard pattern to convert.</param>
- /// <returns>A regex equivalent of the given wildcard.</returns>
- public static string WildcardToRegex(string pattern)
- {
- return "^" + Regex.Escape(pattern).
- Replace("\\*", ".*").
- Replace("\\?", ".") + "$";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment