簡體   English   中英

如何創建在字符串后返回數字的正則表達式模式-C#

[英]How to create a Regex pattern that returns digits after string - C#

我正在嘗試創建一個模式,以返回給我的結果,如下所示:

Help # 7256
Help # 83930
ph  # 7222
this is a test example
Help # 029299
New # 92929

輸出:

Help # 7256 
Help # 83930 
Help # 029299

以幫助開頭,后跟#號,后跟3,4,5位數字的任何值

我嘗試過這樣的事情

Regex pattern = new Regex(@"(Help #) (^|\D)(\d{3, 4,5})($|\D)");

有人可以幫我創建這個圖案嗎? (在C#中)

/^Help\s*#\s*(\d{3,5})/gm

演示版

我應該補充一點,即使它包含6個字符,它也可以與OP中指定的Help # 029299匹配。

如果你只想匹配3到5個字符,這將做到這一點:

/^Help\s*#\s*(\d{3,5})\b/gm

演示版

注意 :如果只希望匹配“ Help[SPACE]#[SPACE]number ”,則只需刪除所有\\s*

一個簡單的解決方案,假設您希望獲取以Help #開頭的所有行(不管后面是什么),並且輸入文件的格式是一致的:

if (currentLine.StartsWith(@"Help #"))
{
    // Do something with the line
}

String.StartsWith方法參考。

如果要使用正則表達式解決方案,請使用以下正則表達式(以字符串形式):

@"^Help #\s+(\d+)"

可以與Regex.Match(String)一起使用 您可以從捕獲組1中提取號碼。此號碼只能匹配以Help #開頭的行,后跟任意數量的空格,然后至少是1位數字。 請注意,僅當逐行掃描文件時,才可以使用此正則表達式。

如果必須將其限制為3-5位數字:

@"^Help #\s+(\d{3,5})"

對於C#,請嘗試以下操作:

var list = new string[] { 
    "Help", "Help # 7256", "Help # 83930", 
    "ph # 7222", "this is a test example", 
    "Help # 029299", "New # 92929",
    "Help # 7256 8945", "Help # 83930 8998 787989"
};

// bear in mind that the $ at the end matches only these strings
// if you want it to match something like Help # 1284 12841 0933 SUBJECT HERE"
// then remove the $ from the end of this pattern
const string pattern = @"^(Help)\s#\s(\d{3,6})\s?(\d{3,6})?\s?(\d{3,6})?$";

var regex = new Regex(pattern);
foreach (string s in list)
{
    if (regex.Match(s).Success)
        Console.WriteLine(s);
}
Console.WriteLine("Done.");
Console.ReadKey();

輸出:

Help # 7256
Help # 83930
Help # 029299
Help # 7256 8945
Help # 83930 8998 787989

暫無
暫無

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

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