簡體   English   中英

正則表達式解析字符串輸入

[英]Regex to parse string input

我想使用正則表達式將其解析為組

string input = @"(1,2)(3,4)";
Regex.Matches(input, @"\((\d,\d)\)");

我得到的結果不僅是1,2和3,4,而且還有空格。 你們能幫我嗎?

編輯:

我想得到2組1,2和3,4。

string input = @"(1,2)(3,4)";
 MatchCollection inputMatch= Regex.Matches(collegeRecord.ToString(), @"(?<=\().*?(?=\))");

對於當前字符串,您將獲得兩個輸出:

inputMatch[0].Groups[0].Value;
inputMatch[0].Groups[1].Value;

要么

您也可以嘗試foreach循環

 foreach (Match match in inputMatch)
{

}

我尚未測試此代碼,

我的工作示例:

MatchCollection facilities = Regex.Matches(collegeRecord.ToString(), @"<td width=""38"">(.*?)image_tooltip");
            foreach (Match facility in facilities)
            {
                collegeDetailDH.InsertFacilityDetails(collegeDetailDH._CollegeID, facility.ToString().Replace("<td width=\"38\">", string.Empty).Replace("<span class=\"icon_", string.Empty).Replace("image_tooltip", string.Empty));
            }

您如何到達他們? 嘗試這個:

例:

MatchCollection matchs = Regex.Matches(input, @"\((\d,\d)\)");
foreach (Match m in matchs)
{
    rtb1.Text += "\n\n" + m.Captures[0].Value;
}

嘗試看這種模式:

(\((?:\d,\d)\))+

+允許該組重復,並且可以出現一次或多次。

您需要使用環顧四周。

string input = @"(1,2)(3,4)";
foreach (Match match in Regex.Matches(input, @"(?<=\().*?(?=\))"))
    Console.WriteLine(match.Value);

如果字符串中可能包含其他內容,然后括號中的數字,並且只需要包含數字的內容,則可以按如下方式使用更具體的正則表達式。

string input = @"(1,2)(3,4)";
foreach (Match match in Regex.Matches(input, @"(?<=\()\d,\d(?=\))"))
    Console.WriteLine(match.Value);

暫無
暫無

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

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