簡體   English   中英

C#正則表達式匹配字符串中多個數字中的單個數字

[英]C# Regex to match single number among multiple numbers in a string

我可以使用什么 C# 正則表達式匹配“字符串 + 一些數字 + 字符串 + 一些數字 + 字符串”

樣本輸入:

Book a hotel room for 10 people  -- o/p: 10
Book a hotel room for 15 people at 10AM -- o/p: 15
Book a hotel room for 5 employees for 12 dec at 10 am -- o/p: 5
Book a hotel room in Singapore for 10 people at today -- o/p: 10
Book a hotel room for  12 dec for 10 members -- o/p: 10 

所以必須獲取多少會員/人/員工來預訂酒店。

希望這是有道理的

我可以插入 C# 的正則表達式會很棒

我嘗試了以下模式但不匹配。

[A-Za-z]*\d+\s?(people)|(memebers)|(peoples)|(member)*$

如果您的號碼總是在關鍵字之前,您可能不需要正則表達式。

試試下面的代碼。

var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var index = Array.Find(parts, p => p == "member" || p == "members" || p == "people");
int count = -1;
var found = index > 0 && int.TryParse(parts[index-1], out count);

如果found為真,則表示 count 具有您可以稍后使用的有效值。

嘗試以下:

            string[] inputs = {
                                 "Book a hotel room for 10 people  -- o/p: 10",
                                 "Book a hotel room for 15 people at 10AM -- o/p: 15",
                                 "Book a hotel room for 5 employees for 12 dec at 10 am -- o/p: 5",
                                 "Book a hotel room in Singapore for 10 people at today -- o/p: 10",
                                 "Book a hotel room for  12 dec for 10 members -- o/p: 10"
                              };

            string pattern = @"for\s+(?'count'\d+)\s+(?'type'[^\s]+)";

            foreach(string input in inputs)
            {
                MatchCollection matches = Regex.Matches(input, pattern);
                foreach (Match match in matches.Cast<Match>().AsEnumerable())
                {
                    Console.WriteLine("Count : '{0}', Type : '{1}'", match.Groups["count"].Value, match.Groups["type"].Value);
                }
            }
            Console.ReadLine();

在組(member)* *之后使用星號*將重復組 0 次或更多次,因此您可以省略它。

在成員(member)$ $之后使用$只會在字符串的末尾匹配它。

您可以使用交替來匹配帶有可選s人員、成員或帶有可選s員工

如果您還想捕獲數字以進行進一步處理,您還可以為該部分使用捕獲組。

\b[A-Za-z]*(\d+)\s?(people|members?|employees?)\b

正則表達式演示| C# 演示

在此處輸入圖片說明

例如

string pattern = @"\b[A-Za-z]*(\d+)\s?(people|members?|employees?)\b";
string input = @"Book a hotel room for 10 people  -- o/p: 10
Book a hotel room for 15 people at 10AM -- o/p: 15
Book a hotel room for 5 employees for 12 dec at 10 am -- o/p: 5
Book a hotel room in Singapore for 10 people at today -- o/p: 10
Book a hotel room for  12 dec for 10 member -- o/p: 10 ";

foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine("Match: {0}\nGroup 1: {1}\nGroup: {2}", m.Value, m.Groups[1].Value, m.Groups[2].Value);
}

如果所有匹配項都以for開頭for您也可以使用

\bfor (\d+)\s?(people|members?|employees?)\b

如果你只想要數字,而不是捕捉其他很多東西,也許你正在尋找這樣的東西

(?<=for)(?: +)(?<number>\d+)(?= +(?:people|employee|member)s?)

暫無
暫無

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

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