当前位置: 首页>>代码示例>>C#>>正文


C# Regex类代码示例

本文整理汇总了C#中Regex的典型用法代码示例。如果您正苦于以下问题:C# Regex类的具体用法?C# Regex怎么用?C# Regex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Regex类属于命名空间,在下文中一共展示了Regex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TcmUri

	public TcmUri(string Uri)
	{
		Regex re = new Regex(@"tcm:(\d+)-(\d+)-?(\d*)-?v?(\d*)");
		Match m = re.Match(Uri);
		if (m.Success)
		{
			PublicationId = Convert.ToInt32(m.Groups[1].Value);
			ItemId = Convert.ToInt32(m.Groups[2].Value);
			if (m.Groups.Count > 3 && !string.IsNullOrEmpty(m.Groups[3].Value))
			{
				ItemTypeId = Convert.ToInt32(m.Groups[3].Value);
			}
			else
			{
				ItemTypeId = 16;
			}
			if (m.Groups.Count > 4 && !string.IsNullOrEmpty(m.Groups[4].Value))
			{
				Version = Convert.ToInt32(m.Groups[4].Value);
			}
			else
			{
				Version = 0;
			}
		}
	}
开发者ID:flaithbheartaigh,项目名称:dynamic-delivery-4-tridion,代码行数:26,代码来源:TcmUri.cs

示例2: Main

 static void Main(string[] args)
 {
     using (StreamReader reader = File.OpenText(args[0]))
         while (!reader.EndOfStream)
         {
             string[] line = reader.ReadLine().Split(',');
             Regex regex = new Regex(@"[0-9]+");
             List<string> words = new List<string>();
             List<string> numbers = new List<string>();
             for (int i = 0; i < line.Length; i++)
             {
                 if (regex.IsMatch(line[i]))
                     numbers.Add(line[i]);
                 else
                     words.Add(line[i]);
             }
             string left = string.Join(",", words.ToArray<string>());
             string right = string.Join(",", numbers.ToArray<string>());
             if (string.IsNullOrEmpty(left))
                 Console.WriteLine(right);
             else if (string.IsNullOrEmpty(right))
                 Console.WriteLine(left);
             else
                 Console.WriteLine(left + "|" + right);
         }
 }
开发者ID:Oscarbralo,项目名称:TopBlogCoder,代码行数:26,代码来源:Program.cs

示例3: Main

    static void Main()
    {
        string input = Console.ReadLine();
            var validUsernames = new List<string>();

            string pattern = @"[\w\d]{2,24}";
            Regex rgx = new Regex(pattern);
            MatchCollection matches = rgx.Matches(input);

            foreach (var match in matches)
            {
                if (char.IsLetter(match.ToString().First()))
                {
                    validUsernames.Add(match.ToString());
                }
            }
            int sum = 0;
            int index = 0;
            for (int i = 0; i < validUsernames.Count-1; i++)
            {
                int currentSum = validUsernames[i].Length + validUsernames[i + 1].Length;
                if (currentSum > sum)
                {
                    sum = currentSum;
                    index = i;
                }
            }
            Console.WriteLine(validUsernames[index]);
            Console.WriteLine(validUsernames[index+1]);
    }
开发者ID:alvelchev,项目名称:SoftUni,代码行数:30,代码来源:ValidUsernames.cs

示例4: RegexMatch

	/// <summary>
	/// 
	/// </summary>
	/// <param name="String"></param>
	/// <param name="RegexString"></param>
	/// <returns></returns>
	public static GroupCollection RegexMatch(this String String, string RegexString)
	{
		var Regex = new Regex(RegexString, RegexOptions.None);
		var Match = Regex.Match(String);
		if (Match == Match.Empty) return null;
		return Match.Groups;
	}
开发者ID:soywiz,项目名称:csharputils,代码行数:13,代码来源:StringExtensions.cs

示例5: CountWords

    //Write a program that reads a list of words from a file words.txt and finds how many times 
    //each of the words is contained in another file test.txt. The result should be written in 
    //the file result.txt and the words should be sorted by the number of their occurrences in 
    //descending order. Handle all possible exceptions in your methods.

    private static Dictionary<string, int> CountWords(string inputPath, string listOfWordsPath)
    {
        List<string> list = ExtractList(listOfWordsPath);
        StreamReader reader = new StreamReader(inputPath);
        Dictionary<string, int> result = new Dictionary<string, int>();

        using (reader)
        {
            while (reader.Peek() != -1)
            {
                string currline = reader.ReadLine();

                for (int i = 0; i < list.Count; i++)
                {
                    Regex word = new Regex("\\b" + list[i] + "\\b");

                    foreach (Match match in word.Matches(currline))
                    {
                        //for each word met, if already met - increase counter, else - start counting it
                        if (result.ContainsKey(list[i]))
                        {
                            result[list[i]]++;
                        }
                        else
                        {
                            result.Add(list[i], 1);
                        }
                    }
                }
            }
        }
        return result;
    }
开发者ID:Varbanov,项目名称:TelerikAcademy,代码行数:38,代码来源:CountSomeWordsInFile.cs

示例6: Main

 static void Main(string[] args)
 {
     string text = Console.ReadLine();
     string pattern = (@"(.)\1+");
     Regex regex = new Regex(pattern);
     Console.WriteLine(regex.Replace(text, "$1"));
 }
开发者ID:zhecho1215,项目名称:Softuni,代码行数:7,代码来源:SeriesOfLetters.cs

示例7: Main

    static void Main()
    {
        StringBuilder line = new StringBuilder();
        string pattern = @"(?<![a-zA-Z])[A-Z]+(?![a-zA-Z])";
        Regex regex = new Regex(pattern);

        while (line.ToString() != "END")
        {          
            MatchCollection matches = regex.Matches(line.ToString());

            int offset = 0;
            foreach (Match match in matches)
            {
               string word = match.Value;
               string reversed = Reverse(word);
              
                if (reversed == word)
                {
                    reversed = DoubleEachLetter(reversed);
                }

                int index = match.Index;
                line = line.Remove(index + offset, word.Length);
                line = line.Insert(index + offset, reversed);
                offset += reversed.Length - word.Length;

            }

            Console.WriteLine(SecurityElement.Escape(line.ToString()));
            line = new StringBuilder(Console.ReadLine());
        }
    }
开发者ID:mdamyanova,项目名称:Fundamental-Level,代码行数:32,代码来源:UppercaseWords.cs

示例8: Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException

 public static void Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException()
 {
     Regex regex = new Regex("e");
     MatchCollection matches = regex.Matches("dotnet");
     Assert.Throws<ArgumentOutOfRangeException>("i", () => matches[-1]);
     Assert.Throws<ArgumentOutOfRangeException>("i", () => matches[matches.Count]);
 }
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:MatchCollectionTests.cs

示例9: IsIPAddress

 public static bool IsIPAddress(string str1)
 {
     if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
         string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
         Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
         return regex.IsMatch(str1);
 }
开发者ID:ryutokeni,项目名称:glw,代码行数:7,代码来源:LoginPage.cs

示例10: ReplaceLinkTags

    static void ReplaceLinkTags(ref string html)
    {
        string pattern = @"<a\s+href=\""(.+)\"">(.+)<\/a>";
        var regex = new Regex(pattern);

        html = regex.Replace(html, "[URL href=$1]$2[/URL]");
    }
开发者ID:AngelZapryanov,项目名称:SoftUni-Homeworks,代码行数:7,代码来源:ReplaceHtmlATags.cs

示例11: Main

    static void Main()
    {
        string input = Console.ReadLine();
        string pattern = @"<a\s+href=([^>]+)>([^<]+)</a>";
        Regex regex = new Regex(pattern);
        string replacement = "[URL href=$1]$2[/URL]";
        string result = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(result);

        //Console.WriteLine("Enter HTML document");
        //string textHTML = Console.ReadLine();
        //string output = string.Empty;
        //int counter = 0;
        //while (textHTML.IndexOf("<a href=\"", counter) > 0)
        //{
        //    output = textHTML.Replace("<a href=\"", "[URL=");
        //    counter++;
        //}
        //counter = 0;
        //while (output.IndexOf("\">", counter) > 0)
        //{
        //    output = output.Replace("\">", "]");
        //    counter++;
        //}
        //counter = 0;
        //while (output.IndexOf("</a>", counter) > 0)
        //{
        //    output = output.Replace("</a>", "[/URL]");
        //    counter++;
        //}
        //Console.WriteLine(output);
    }
开发者ID:LPetrova,项目名称:CSharpAdvance,代码行数:32,代码来源:ReplaceTag.cs

示例12: IsSentence

 private static MatchCollection IsSentence(string text)
 {
     string pattern = @"([^.!?]+(?=[.!?])[.!?])";
     Regex rgx = new Regex(pattern);
     MatchCollection matches = rgx.Matches(text);
     return matches;
 }
开发者ID:KatyaMarincheva,项目名称:CSharp-Advanced,代码行数:7,代码来源:SentenceExtractor.cs

示例13: Main

    public static void Main()
    {
        while (true)
        {
            string[] input = Console.ReadLine().Split(' ');
            if (input[0] == "END")
            {
                break;
            }
            for (int i = 0; i < input.Length; i++)
            {
                string pattern = @"\b(?:\d*|\W*)([A-Z]{1,})(?:\d*|\W*)\b";
                Regex regex = new Regex(pattern);
                MatchCollection matches = regex.Matches(input[i]);
                foreach (Match match in matches)
                {
                    string oldString = match.Groups[1].ToString();
                    string reverse = new string(oldString.Reverse().ToArray());
                    if (match.Groups[1].Length == 1 || oldString.Equals(reverse))
                    {
                        string newString = ReplaceWithDoubleLetters(oldString);
                        input[i] = input[i].Replace(oldString, newString);
                    }
                    else
                    {
                        input[i] = input[i].Replace(oldString, reverse);
                    }
                }
            }

            Console.WriteLine(SecurityElement.Escape(string.Join(" ", input)));
        }
    }
开发者ID:IskraNikolova,项目名称:Advanced-CSharp,代码行数:33,代码来源:UppercaseWords.cs

示例14: RegexGroup

 public static SqlChars RegexGroup( SqlChars input, SqlString pattern, SqlString name )
 {
     Regex regex = new Regex( pattern.Value, Options );
       Match match = regex.Match( new string( input.Value ) );
       return match.Success ?
         new SqlChars( match.Groups[name.Value].Value ) : SqlChars.Null;
 }
开发者ID:remifrazier,项目名称:SPCClogin_Public,代码行数:7,代码来源:RegexGroup.cs

示例15: Main

    static void Main()
    {
        const string Keys = @"(?<startKey>^[A-Za-z_]*)(?=\d).*(?<=\d)(?<endKey>[A-Za-z_]*)";
        var keysMatcher = new Regex(Keys);

        string keysString = Console.ReadLine();
        string startKey = keysMatcher.Match(keysString).Groups["startKey"].Value;
        string endKey = keysMatcher.Match(keysString).Groups["endKey"].Value;

        if (string.IsNullOrEmpty(startKey) || string.IsNullOrEmpty(endKey))
        {
            Console.WriteLine("<p>A key is missing</p>");
            return;
        }

        string Pattern = string.Format("(?:{0}){1}(?:{2})", startKey, @"(\d*\.?\d+)", endKey);
        var numbersMatcher = new Regex(Pattern);

        string textString = Console.ReadLine();
        var matches = numbersMatcher.Matches(textString);

        var numbers = (from Match number in matches select double.Parse(number.Groups[1].Value)).ToList();

        if (numbers.Count == 0)
        {
            Console.WriteLine("<p>The total value is: <em>nothing</em></p>");
        }
        else
        {
            double sum = numbers.Sum();
            Console.WriteLine("<p>The total value is: <em>{0}</em></p>",sum);
        }
    }
开发者ID:alvelchev,项目名称:SoftUni,代码行数:33,代码来源:SumOfAllValues.cs


注:本文中的Regex类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。