簡體   English   中英

C#Regex如何捕獲* |之間的所有內容 和| *?

[英]How can C# Regex capture everything between *| and |*?

在C#中,我需要在短語* |​​ variablename | *中捕獲variablename。

我有這個RegEx: Regex regex = new Regex(@"\\*\\|(.*)\\|\\*");

在線正則表達式測試者返回“variablename”,但在C#代碼中,它返回* | variablename | *,或包含星號和條形字符的字符串。 任何人都知道我為什么會遇到這個回報值?

非常感謝!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegExTester
{
    class Program
    {
        static void Main(string[] args)
        {
            String teststring = "This is a *|variablename|*";
            Regex regex = new Regex(@"\*\|(.*)\|\*");
            Match match = regex.Match(teststring);
            Console.WriteLine(match.Value);
            Console.Read();
        }
    }
}

//Outputs *|variablename|*, instead of variablename

match.Value包含整個匹配。 這包括自您在正則表達式中指定它們以來的分隔符。 當我測試你的正則表達式並使用RegexPal輸入時,它會突出顯示*|variablename|*

您只想獲取捕獲組(括號中的內容),因此請使用match.Groups[1]

String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Groups[1]);

暫無
暫無

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

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