簡體   English   中英

如何使用Regex僅獲取字符串開頭和結尾的數字?

[英]How to get only numbers at the beginning and end of a character in string with Regex?

Example String : "as8d79asf5.dfdg dg s dgd2011/25klsdsj jdıo84823 jhgfkasfsf 2001/26llkasdjfıo";

我只想從字符串中獲取數字。

結果:

  1. 2011/25
  2. 2001/26

編輯:

字符串中的字符數不清楚。 例如:2 / 1234、214 / 1、22 / 2545。 可能是全部。

我如何得到這個結果?

這應該可以解決問題:

\d+/\d+

否則,如果您正好尋找4位/ 2位:

\d{4}/\d{2}

僅使用@"\\d+/\\d+"就足夠了

您可以使用類似(C#引用)的表達式:

@"\d{4}/\d\d"

與“字符的開始和結束”無關的算法。

嘗試以下方法。

string input="as8d79asf5.dfdg dg s dgd2011/25klsdsj jdıo84823 jhgfkasfsf 2001/26llkasdjfıo";
        Regex nmRegex = new Regex(@"([\d]+/[\d]+)");
        var matches = nmRegex.Matches(input);
        List<string> matchedStrings = new List<string>();

        for (int i = 0; i < matches.Count; i++)
        {
            var g = matches[i].Groups;
            if (g.Count > 0)
                matchedStrings.Add(g[1].Value);
        }

像這樣的正則表達式可能?

([[0-9]{4}\/[0-9]{2})

雖然在C#中不是很可靠。

暫無
暫無

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

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