1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System.Text.RegularExpressions;
- namespace Common
- {
- /// <summary>
- /// 操作正则表达式的公共类
- /// </summary>
- public class RegexHelper
- {
- #region 验证输入字符串是否与模式字符串匹配
- /// <summary>
- /// 验证输入字符串是否与模式字符串匹配,匹配返回true
- /// </summary>
- /// <param name="input">输入的字符串</param>
- /// <param name="pattern">模式字符串</param>
- /// <param name="options">筛选条件</param>
- public static bool IsMatch(string input, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
- {
- return Regex.IsMatch(input, pattern, options);
- }
- /// <summary>
- /// 获取第一个匹配到的字符串
- /// </summary>
- /// <param name="input"></param>
- /// <param name="pattern"></param>
- /// <param name="options"></param>
- /// <returns></returns>
- public static string GetMatchResult(string input, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
- {
- if (IsMatch(input, pattern))
- {
- Regex regex = new Regex(pattern, options);
- MatchCollection collection = regex.Matches(input);
- GroupCollection groupCollection = collection[0].Groups;
- return groupCollection[0].Value;
- }
- return "";
- }
- #endregion
- }
- }
|