簡體   English   中英

在具有特殊模式C#的字符串中查找字符串

[英]Find a string in a string with special pattern C#

我在C#中有一個長字符串,我需要找到看起來像這樣的子字符串:

number.number:number

例如,以下字符串:

text text
965.435:001 text text sample
7854.66:006 text text

我想找到965.435:001和7854.66:006並將其保存到字符串中。

  • \\d表示“數字”
  • +表示“一個或多個”
  • \\. 表示文字點( .單獨表示“任何字符”)
  • \\b表示“單詞邊界”(字母數字“單詞”的開頭或結尾)。

因此,您的正則表達式將是

\b\d+\.\d+:\d+\b

在C#中:

MatchCollection allMatchResults = null;
Regex regexObj = new Regex(@"\b\d+\.\d+:\d+\b");
allMatchResults = regexObj.Matches(subjectString);
if (allMatchResults.Count > 0) {
    // Access individual matches using allMatchResults.Item[]
} else {
    // Match attempt failed
}

下面的示例中如何使用正則表達式在字符串中查找某些格式

class TestRegularExpressionValidation
{
    static void Main()
    {
        string[] numbers = 
        {
            "123-456-7890", 
            "444-234-22450", 
            "690-203-6578", 
            "146-893-232",
            "146-839-2322",
            "4007-295-1111", 
            "407-295-1111", 
            "407-2-5555", 
        };

        string sPattern = "^\\d{3}-\\d{3}-\\d{4}$";

        foreach (string s in numbers)
        {
            System.Console.Write("{0,14}", s);

            if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))
            {
                System.Console.WriteLine(" - valid");
            }
            else
            {
                System.Console.WriteLine(" - invalid");
            }
        }
    }
}

使用正則表達式並捕獲東西。

玩這段代碼...它將為您帶來想要的...

 string text = "your text";
      string pat = @"(\d*\.\d*:\d*)";

      // Instantiate the regular expression object.
      Regex r = new Regex(pat, RegexOptions.IgnoreCase);

      // Match the regular expression pattern against a text string.
      Match m = r.Match(text);
      int matchCount = 0;
      while (m.Success) 
      {
         Console.WriteLine("Match"+ (++matchCount));
         for (int i = 1; i <= 2; i++) 
         {
            Group g = m.Groups[i];
            Console.WriteLine("Group"+i+"='" + g + "'");
            CaptureCollection cc = g.Captures;
            for (int j = 0; j < cc.Count; j++) 
            {
               Capture c = cc[j];
               System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
            }
         }
         m = m.NextMatch();
      }

像這樣:

var match = Regex.Match("\d+\.\d+:\d+")
while (match.Success){
    numbersList.Add(match.Groups[0])
    match = match.NextMatch()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM