gpt4 book ai didi

c# - 不确定为什么 Regex.Replace() 在使用包含正则表达式模式(涉及捕获组)的字典时不起作用

转载 作者:行者123 更新时间:2023-12-05 04:19:41 25 4
gpt4 key购买 nike

所以我正在尝试编写一种使用正则表达式将“100¢”替换为“100 美分”的方法。我使用的模式是 (\d+)(¢)。最重要的是,我还试图替换其他东西,所以我需要一个字典数据结构来保存所有这些正则表达式模式作为键,以及我想要替换它们的值作为字典值。

我目前的代码是这样的:

        var replacementsMap = new Dictionary<string, string>()
{
{@"(\d+)(¢)", "$1 cents"}
};

字典中会有更多内容,但为了简单起见,我将只添加一个模式值对。我正在使用反向引用来让第一个捕获组在其后带有“cents”而不是符号。

例如:5¢ -> 5 美分

要替换,我是这样做的:

        string input = "100¢";
Console.WriteLine(input); //showing original input


var regex = new Regex(String.Join("|",replacementsMap.Keys));

var newStr = regex.Replace(input, m => replacementsMap[m.Value]);
Console.WriteLine(newStr); //showing new input

我得到的错误是这样的,我不确定我的实现哪里出了问题:

Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key '100¢' was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Program.<>c__DisplayClass1_0.<Main>b__0(Match m) in Program.cs:line 79
at System.Text.RegularExpressions.Regex.<>c.<Replace>b__99_0(ValueTuple`5& state, Match match)
at System.Text.RegularExpressions.Regex.RunAllMatchesWithCallback[TState](String inputString, ReadOnlySpan`1 inputSpan, Int32 startat, TState& state, MatchCallback`1 callback, RegexRunnerMode mode, Boolean reuseMatchObject)
at System.Text.RegularExpressions.Regex.RunAllMatchesWithCallback[TState](String input, Int32 startat, TState& state, MatchCallback`1 callback, RegexRunnerMode mode, Boolean reuseMatchObject)
at System.Text.RegularExpressions.Regex.Replace(MatchEvaluator evaluator, Regex regex, String input, Int32 count, Int32 startat)
at System.Text.RegularExpressions.Regex.Replace(String input, MatchEvaluator evaluator)
at Program.Main() in Program.cs:line 79

最佳答案

问题是当你有一个匹配项时,这个匹配项不包含有关匹配的原始模式的信息。因此,您无法在字典中进行查找,因为您没有在字典中用作键的模式。

解决方案:将模式组合成一个时,用命名的捕获组包围每个模式。名称基于模式列表中的模式索引。

然后您可以从匹配信息中获取该名称,使用自动生成的名称从列表中检索原始模式和替换模式,并将单独的模式应用于匹配值。

示例代码:

string input = "I have 5$ and 4€ and 6¢";

// Use a List instead of Dictionary so we can retrieve the entries by index
List<(string pattern, string replacement)> replacementInstructions = new List<(string pattern, string replacement)> {
(@"(\d+)(¢)", "$1 cents"),
(@"(\d+)(€)", "$1 euros"),
(@"(\d+)(\$)", "$1 dollars"),
};

// Create combined pattern with auto-named groups
StringBuilder builder = new StringBuilder();

for(int i=0; i < replacementInstructions.Count; i++)
{
if(i > 0) builder.Append("|");

var (pattern, _) = replacementInstructions[i];

string groupName = "GN" + i;
builder.Append("(?<" + groupName + ">" + pattern + ")");
}

string combinedPattern = builder.ToString();
Console.WriteLine("Combined Pattern: " + combinedPattern);

// Declare callback that will do the replacement
MatchEvaluator evaluator = (Match match) =>
{
// Get named group that matched and its name
Group group = (from Group g in match.Groups
where g.Success &&
g.Name.StartsWith("GN")
select g).First();
string groupName = group.Name;

// Get number from groupname
// and then entry from replacementInstructions based on number
string numberString = groupName.Substring(2);
int number = int.Parse(numberString);
var (pattern, replacement) = replacementInstructions[number];

// Apply replacement pattern on match
return Regex.Replace(match.Value, pattern, replacement);
};


// Replace
string result = Regex.Replace(input, combinedPattern, evaluator);

Console.WriteLine("Result: " + result);

输出:

Combined Pattern: (?<GN0>(\d+)(¢))|(?<GN1>(\d+)(€))|(?<GN2>(\d+)(\$))
Result: I have 5 dollars and 4 euros and 6 cents

关于c# - 不确定为什么 Regex.Replace() 在使用包含正则表达式模式(涉及捕获组)的字典时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74737476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com