search in a string and find all matched elements - CSharp System

CSharp examples for System:String Match

Description

search in a string and find all matched elements

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;/*from   ww w  .  j a va  2 s .co  m*/

public class Main{
        /// <summary>
        /// search in a string and find all matched elements
        /// </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 strings</returns>
        public static string[] Matches(this string source, string pattern, RegexOptions option)
        {
            if (string.IsNullOrEmpty(source))
            {
                return new string[0];
            }

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

            var matches = Regex.Matches(source, pattern, option);
            return (from Match m in matches
                    where m.Success
                    from g in m.Groups.Cast<Group>().Skip(m.Groups.Count > 1 ? 1 : 0)
                    select g.Value).ToArray();
        }
        /// <summary>
        /// search in a string and find all matched elements
        /// </summary>
        /// <param name="source">source string</param>
        /// <param name="pattern">regex match format pattern</param>
        /// <returns>matched strings</returns>
        public static string[] Matches(this string source, string pattern)
        {
            return source.Matches(pattern, RegexOptions.None);
        }
}

Related Tutorials