簡體   English   中英

C#正則表達式。大括號{}和mod(%)字符內的所有內容

[英]C# regex. Everything inside curly brackets{} and mod(%) charaters

我試圖在同一個正則表達式中獲取{}和%%之間的值。 這就是我現在所擁有的。 我可以成功地為每個人獲得價值,但我很想知道如何將兩者結合起來。

var regex = new Regex(@"%(.*?)%|\{([^}]*)\}");

String s = "This is a {test} %String%. %Stack% {Overflow}";

上述字符串的預期答案

test
String
Stack
Overflow

個人正則表達式

@"%(.*?)%" gives me String and Stack
@"\{([^}]*)\}" gives me test and Overflow

以下是我的代碼。

var regex = new Regex(@"%(.*?)%|\{([^}]*)\}");
var matches = regex.Matches(s); 
foreach (Match match in matches) 
{
    Console.WriteLine(match.Groups[1].Value);
}

與你的正則表達式相似。 您可以使用命名捕獲組

String s = "This is a {test} %String%. %Stack% {Overflow}";
var list = Regex.Matches(s, @"\{(?<name>.+?)\}|%(?<name>.+?)%")
           .Cast<Match>()
           .Select(m => m.Groups["name"].Value)
           .ToList();

如果您想了解條件表達式的工作原理,下面是使用這種.NET正則表達式功能的解決方案:

(?:(?<p>%)|(?<b>{))(?<v>.*?)(?(p)%|})

請參閱正則表達式演示

下面是它的工作原理:

  • (?:(?<p>%)|(?<b>{)) - 匹配並捕獲組“p”與% (百分比),或組“b”(大括號)與{
  • (?<v>.*?) - 匹配並捕獲到組“v”(值)任何字符(甚至是換行符,因為我將使用RegexOptions.Singleline )零次或多次,但盡可能少(懶惰匹配) *?量詞)
  • (?(p)%|}) - 條件表達式含義:如果“p”組匹配,則匹配% ,否則匹配}

在此輸入圖像描述

C#demo

var s = "This is a {test} %String%. %Stack% {Overflow}";
var regex = "(?:(?<p>%)|(?<b>{))(?<v>.*?)(?(p)%|})";
var matches = Regex.Matches(s, regex, RegexOptions.Singleline); 
// var matches_list = Regex.Matches(s, regex, RegexOptions.Singleline)
//                 .Cast<Match>() 
//                 .Select(p => p.Groups["v"].Value)
//                 .ToList(); 
// Or just a demo writeline
foreach (Match match in matches) 
    Console.WriteLine(match.Groups["v"].Value);

有時候捕獲是在第1組中,有時它在第2組中,因為你有兩對括號。

如果您這樣做,原始代碼將起作用:

Console.WriteLine(match.Groups[1].Value + match.Groups[2].Value);

因為一個組將是空字符串,另一個組將是您感興趣的值。

@"[\{|%](.*?)[\}|%]"

這個想法是:

{ or %
anything
} or %

我認為你應該使用條件和嵌套組的組合:

((\{(.*)\})|(%(.*)%))

暫無
暫無

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

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