[英]How to extract values in string by using Regular Expression
我有一個看起來像的字符串:
(Service=[MyCar]&(Type=[News]|Type=[Review]))
我需要獲取 Type 的值,可能有 1 種類型或多種類型。
我目前的正則表達式是:
/Type=[(News|Review|Video)]*/g
它不返回值,而是返回“Type=”
使用MatchCollection
和前綴括號[]
與反斜杠\\
string input = "(Service=[MyCar]&(Type=[News]|Type=[Review]))";
string pattern = @"Type=\[(News|Review|Video)\]";
MatchCollection matches = Regex.Matches(input, pattern);
foreach(Match match in matches)
{
foreach(Group group in match.Groups)
{
Console.WriteLine(group);
}
}
像這樣的圖案
類型=[(\\w*)]
會給你組。 你可以看看這里的表達。 你也可以在dotnetfiddle測試這個 C# 代碼
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "(Service=[CarSales]&(Type=[News]|Type=[Review]))";
string pattern = @"Type=\[(\w*)\]";
MatchCollection matches = Regex.Matches(input, pattern);
foreach(Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}
您可以在 MSDN“Match.Groups 屬性”頁面上找到有關組和索引的一些信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.