![](/img/trans.png)
[英]why is the pattern being printed along with the matches in RegEx.Matches
[英]Determining which pattern matched using Regex.Matches
我正在寫一個翻譯,而不是任何嚴肅的項目,只是為了好玩,並且對正則表達式更加熟悉。 從下面的代碼中我想你可以找到我要去的地方(cheezburger有人嗎?)。
我正在使用一個字典,它使用正則表達式列表作為鍵,字典值是一個List<string>
,它包含一個替換值的進一步列表。 如果我打算這樣做,為了弄清楚替補是什么,我顯然需要知道關鍵是什么,我怎樣才能找出觸發匹配的模式?
var dictionary = new Dictionary<string, List<string>>
{
{"(?!e)ight", new List<string>(){"ite"}},
{"(?!ues)tion", new List<string>(){"shun"}},
{"(?:god|allah|buddah?|diety)", new List<string>(){"ceiling cat"}},
..
}
var regex = "(" + String.Join(")|(", dictionary.Keys.ToArray()) + ")";
foreach (Match metamatch in Regex.Matches(input
, regex
, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
{
substitute = GetRandomReplacement(dictionary[ ????? ]);
input = input.Replace(metamatch.Value, substitute);
}
我正在嘗試什么,或者有更好的方法來實現這種瘋狂嗎?
您可以在正則表達式中為每個捕獲組命名,然后在匹配中查詢每個命名組的值。 這應該可以讓你做你想做的事。
例如,使用下面的正則表達式,
(?<Group1>(?!e))ight
然后,您可以從匹配結果中提取組匹配:
match.Groups["Group1"].Captures
你有另一個問題。 看一下這個:
string s = @"My weight is slight.";
Regex r = new Regex(@"(?<!e)ight\b");
foreach (Match m in r.Matches(s))
{
s = s.Replace(m.Value, "ite");
}
Console.WriteLine(s);
輸出:
My weite is slite.
String.Replace
是一個全局操作,因此即使weight
與正則表達式不匹配,當發現slight
時它仍然會被更改。 您需要同時進行匹配,查找和替換; Regex.Replace(String, MatchEvaluator)
可以讓你這樣做。
像傑夫所說的使用命名組是最強大的方式。
您還可以按編號訪問組,因為它們在您的模式中表示。
(first)|(second)
可以訪問
match.Groups[1] // match group 2 -> second
當然,如果您有更多您不想包含的括號,請使用非捕獲運算符?:
((?:f|F)irst)|((?:s|S)econd)
match.Groups[1].Value // also match group 2 -> second
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.