search in a string and find the first matched element - CSharp System

CSharp examples for System:String Match

Description

search in a string and find the first matched element

Demo Code


using System.Xml;
using System.Web;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*w  ww  .ja  v a  2s  .c o  m*/

public class Main{
        /// <summary>
        /// search in a string and find the first matched element
        /// </summary>
        /// <param name="source">source string</param>
        /// <param name="pattern">regex match format pattern</param>
        /// <param name="option">A bitwise OR combination of the enumeration values for Regular Expression.</param>
        /// <returns>matched string</returns>
        public static string Match(this string source, string pattern, RegexOptions option)
        {
            if (string.IsNullOrEmpty(source))
            {
                return string.Empty;
            }

            if (string.IsNullOrEmpty(pattern))
            {
                return source;
            }

            var match = Regex.Match(source, pattern, option);
            if (match.Success)
            {
                return match.Groups.Count > 1 ? match.Groups[1].Value : match.Value;
            }

            return string.Empty;
        }
        #endregion

        #region Regex Match
        /// <summary>
        /// search in a string and find the first matched element
        /// </summary>
        /// <param name="source">source string</param>
        /// <param name="pattern">regex match format pattern</param>
        /// <returns>matched string</returns>
        public static string Match(this string source, string pattern)
        {
            return source.Match(pattern, RegexOptions.None);
        }
}

Related Tutorials