• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Regex类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: RewriteUrl

        /// <summary>
        /// Rewrites the URL and redirect the request to destination page from rules in web.config
        /// </summary>
        public static void RewriteUrl()
        {
            RewriteConfigurationSection config = (RewriteConfigurationSection)ConfigurationManager.GetSection("rewrite");

            if (config != null)
            {
                if (config.Rules != null)
                {
                    foreach (RewriteRuleElement rule in config.Rules)
                    {
                        Regex r = new Regex(rule.Url, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                        Match m = r.Match(HttpContext.Current.Request.Url.AbsolutePath);
                        if (m.Success)
                        {
                            string destinationUrl = rule.Destination;

                            for (int i = 0; i < m.Groups.Count; i++)
                            {
                                if (m.Groups[i].Index > 0)
                                    destinationUrl = destinationUrl.Replace("$" + i.ToString(), m.Groups[i].Value);
                            }

                            RewriteContext ctx = new RewriteContext();
                            ctx.RewritedUrl = HttpContext.Current.Request.Url.AbsoluteUri;
                            HttpContext.Current.Items.Add("REWRITECONTEXT", ctx);
                            HttpContext.Current.RewritePath(destinationUrl + HttpContext.Current.Request.Url.Query);
                        }
                    }
                }
                else
                    throw new Exception("Cannot find <rules> node in web.config");
            }
            else
                throw new Exception("Cannot find <rewrite> node in web.config");
        }
开发者ID:shardick,项目名称:CodeMakr,代码行数:38,代码来源:URLRewrite.cs


示例17: GetFirstString

 //public void LoadLeft(string name_en_s)
 //{
 //    data_conn cn = new data_conn();
 //    if (name_en_s != "")
 //    {
 //        DataSet ds = cn.mdb_ds("select top 5 * from TB_BBS where title like '%" + name_en_s + "%'", "bbs");
 //        Repeater1.DataSource = ds.Tables["bbs"].DefaultView;
 //        Repeater1.DataBind();
 //        string strYear = DateTime.Now.Year.ToString();
 //        string strMonth = DateTime.Now.Month.ToString();
 //        DataSet ds = cn.mdb_ds("select top 1 * from TB_BAF where months='" + strYear + "-" + strMonth + "' and Carriers like '%" + name_en_s + "%'", "baf");
 //        if (ds.Tables["baf"].Rows.Count > 0)
 //        {
 //            Literal8.Text = "<a href='../baf/#anchor" + ds.Tables["baf"].Rows[0]["id"].ToString() + "'>" + strMonth + "月" + name_en_s + "最新BAF/CAF</a><br />";
 //        }
 //        ds = cn.mdb_ds("select top 1 * from TB_THC where months='" + strYear + "-" + strMonth + "' and Carriers='" + name_en_s + "'", "thc");
 //        if (ds.Tables["thc"].Rows.Count > 0)
 //        {
 //            Literal9.Text = "<a href='../thc/#anchor" + ds.Tables["thc"].Rows[0]["id"].ToString() + "'>" + strMonth + "月" + name_en_s + "最新THC</a><br />";
 //        }
 //        ds = cn.mdb_ds("select top 5 * from TB_Search_Ship order by Num desc", "hot");
 //        Repeater2.DataSource = ds.Tables["hot"].DefaultView;
 //        Repeater2.DataBind();
 //    }
 //}
 public string GetFirstString(string stringToSub,int length)
 {
     Regex regex=new Regex("[\u4e00-\u9fa5\uff00-\uffef\u3000-\u303f\u2000-\u206f\u25a0-\u25ff]+", RegexOptions.Compiled);
     char[] stringChar = stringToSub.ToCharArray();
     StringBuilder sb = new StringBuilder();
     int nLength = 0;
     bool isCut = false;
     for (int i = 0; i < stringChar.Length; i++)
     {
         if (regex.IsMatch((stringChar[i]).ToString()))
         {
             sb.Append(stringChar[i]);
             nLength += 2;
         }
         else
         {
             sb.Append(stringChar[i]);
             nLength = nLength + 1;
         }
         if(nLength >length )
         {
             isCut = true;
             break;
         }
     }
     return sb.ToString();
 }
开发者ID:xiaomincui,项目名称:100allin,代码行数:52,代码来源:ports.aspx.cs


示例18: Main

    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        string concatenated = "";
        for (int i = 0; i < n; i++)
        {
            int number = int.Parse(Console.ReadLine());
            concatenated += Convert.ToString(number, 2).PadLeft(32, '0').Substring(2, 30);//TODO use stringbuilder
        }

        //Console.WriteLine(concatenated);
        Regex reg1 = new Regex(@"(1)\1+");
        MatchCollection matches = reg1.Matches(concatenated);
        int longest1 = 0;
        foreach (System.Text.RegularExpressions.Match match in matches)
        {
            if (longest1 < match.Length) longest1 = match.Length;
        }

        Console.WriteLine(longest1);

        Regex reg2 = new Regex(@"(0)\1+");
        MatchCollection matches2 = reg2.Matches(concatenated);
        int longest2 = 0;
        foreach (System.Text.RegularExpressions.Match match in matches2)
        {
            if (longest2 < match.Length) longest2 = match.Length;
        }

        Console.WriteLine(longest2);
    }
开发者ID:damy90,项目名称:Telerik-all,代码行数:31,代码来源:Program.cs


示例19: LoadPathOfFile

    public static Path LoadPathOfFile(string fileName)
    {
        Path path = new Path();

        using (StreamReader sr = new StreamReader(fileName))
        {
            string input = sr.ReadToEnd();

            string pattern = "{([\\d,.]+), ([\\d,.]+), ([\\d,.]+)}";

            var reg = new Regex(pattern);
            var matchs = reg.Matches(input);

            if (matchs.Count <= 0)
            {
                throw new ApplicationException("Invalid data in file " + fileName);
            }

            foreach (Match match in matchs)
            {
                double x = double.Parse(match.Groups[1].Value);
                double y = double.Parse(match.Groups[2].Value);
                double z = double.Parse(match.Groups[3].Value);

                Point p = new Point(x, y, z);
                path.AddPoint(p);
            }
        }

        return path;
    }
开发者ID:ScreeM92,项目名称:Software-University,代码行数:31,代码来源:Storage.cs


示例20: isFieldValid

 private bool isFieldValid(List<object> fieldTypeValue)
 {
     Regex regEx;
     string fieldValue = (string)fieldTypeValue[2];
     switch ((FieldType)fieldTypeValue[1])
     {
         case FieldType.Integer:
             regEx = new Regex(@"^\d+$");
             return regEx.IsMatch(fieldValue);
             break;
         case FieldType.Phone:
             regEx = new Regex(@"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$");
             return regEx.IsMatch(fieldValue);
             break;
         case FieldType.Email:
             regEx = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
             return regEx.IsMatch(fieldValue);
             break;
         case FieldType.URL:
             regEx = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
             return regEx.IsMatch(fieldValue);
             break;
         case FieldType.SSN:
             regEx = new Regex(@"^\d{3}-\d{2}-\d{4}$");
             return regEx.IsMatch(fieldValue);
             break;
         case FieldType.NonEmptyString:
             return fieldValue.Trim().Length > 0;
             break;
     }
     return true;
 }
开发者ID:therabbitwindfall,项目名称:daleyjem,代码行数:32,代码来源:FormValidator.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# RegexOptions类代码示例发布时间:2022-05-24
下一篇:
C# RegExp类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap