C# 正則Regex、Regex.Match、Match、Match.Groups、GroupCollection.Item 匹配結果指定群組名
阿新 • • 發佈:2019-02-06
public virtual GroupCollection Groups { get; }
Group 型別 GroupCollection屬性(索引):Item[String] 允許通過字串索引訪問集合成員。
Group型別定義:
[SerializableAttribute]
public class Group : Capture
Capture 類:表示單個成功的子表示式捕獲的結果。
string result = "{\"access_token\":\"FQSRXOwxRELZLN9ZfRXm2tWiVajEuk7pesRI74vCrH8sfqL4XqX2_aT_HZOLTmgD5_4s884sYVpBqtZDFNAc1EQTJ84aZTj5GDP7wVg0BgoYoWffgmTQMNik1HtC7mVjzbuYdMzhJxFx - sL6SbodMfd_Yzq_iwuy6rW4Myg0zLsQFKSoyCCHCsIOEzcFI9geKXqvVe8uNQomEhewRQt40Q\",\" expires_in\":7200}";
string regex = "\"access_token\":\"(?<token>.*?)\"";
string token = CRegex.GetText(result, regex, "toke");
public static string GetText(string sInput, string sRegex, string sGroupName)
{
Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
Match mc = re.Match(sInput);
string result = "";
if (mc.Success)
{
if (sGroupName != "")
{
result = mc.Groups[sGroupName].Value;
}
else
{
result = mc.Value;
}
}
return result;
}