簡體   English   中英

如何使用正則表達式提取字符串中的值

[英]How to extract values in string by using Regular Expression

我有一個看起來像的字符串:

(Service=[MyCar]&(Type=[News]|Type=[Review]))

我需要獲取 Type 的值,可能有 1 種類型或多種類型。

我目前的正則表達式是:

/Type=[(News|Review|Video)]*/g

它不返回值,而是返回“Type=”

方括號[]在正則表達式中具有特殊含義,因此需要對其進行轉義:

Type=\[(News|Review|Video)\]

比較這個

有了這個

在第一種情況下,您實際上將列表中的單個字符(News|RviVdo)[(News|Review|Video)]匹配

對於每場比賽,您將在Group[1]找到您要查找的文本

使用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.

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