簡體   English   中英

正則表達式從句子C#中切出單詞

[英]Regex cut the words out of the sentence C#

我有一些句子,我想在C#中提取Regex的一些單詞

像這樣的例子:

// 標准房1人,從18/03/2014至19/03/2014

從句子中取出“ Standard room 1 person”,從xxxx刪除到xxxx

//從2014年3月18日至2014年3月19日的家庭夜間3/4

取得“家庭房”,房間的人數是3/4,我想把4取為房間的最大人數。

對於這兩種情況,from和to都將被忽略。

您能否建議我使用reg ex模式來做那些事情(2例)?

非常感謝,祝您有美好的一天!

如果您不堅持使用正則表達式:

string[] array1 = "Standard room 1 persons from 18/03/2014 to 19/03/2014".Split();
string[] array2 = "Family night room 3/4 from 18/03/2014 to 19/03/2014".Split();

string n = String.Join(" ", array1.TakeWhile(s => s != "from").ToArray());
string n2 = String.Join(" ", array2.TakeWhile(s => s != "from").ToArray());

Console.WriteLine(n);  // Standard room 1 persons 
Console.WriteLine(n2); // Family night room 3/4 

只需使用以下命令:

string s = "//Standard room 1 and 1/4 persons from 18/03/2014 to 19/03/2014";
            string matchedStr = Regex.Match(s, ".*(?=from)(?=.*to)").Value;
            Console.WriteLine(matchedStr);
            string totalStr = Regex.Match(s, ".*(?=from)(?=.*to)").Value;
            int total=Convert.ToInt32(Regex.Match(totalStr,@"(?<=\d/)\d").Value);
            Console.WriteLine(total);

樣例代碼:

string input = "Standard room 1 persons from 18/03/2014 to 19/03/2014"
string s = Regex.Match(input, "(.*)(?=from)").Value;
s = s.Trim();

// Get your maximum number
MatchCollection numbers = Regex.Matches(s, "[\d]");
int max = 0;
foreach (Match number in numbers)
{
     int temp = int.Parse(number.Value);
     if (max > temp)
        max = temp;
}

暫無
暫無

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

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