- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我正在尝试编写一种使用正则表达式将“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/
这个问题不太可能对任何 future 的访客有帮助;它只与一个较小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于全世界的互联网受众。如需帮助使此问题更广泛适用,visit the
我有一个在 ab 时间内运行的算法,其中 a 和 b 都是单独的输入。 我的算法还是多项式时间复杂度算法还是nn?我认为 nn 不是多项式,但我仍然不确定。 我看到 n 算法的阶乘仍然评估为 nn 复
这个问题在这里已经有了答案: Logical operators (AND, OR) with NA, TRUE and FALSE (2 个回答) 1年前关闭。 由于“is.na(NA)”返回真,“
假设我有一个具有以下结构的 Pandas 数据框: df = pd.DataFrame(dict(a=["x", "x", "y"], b=[0, 1, 1], c=[1, 2, 2])) 我想按 a
谁能帮我处理一些相当复杂的 Django 查询? 这些是我的模型: class County(models.Model): name = models.CharField(max_length
我想从某个表中选择一行并根据另一个表对结果进行排序。 这是我的表: lang1_words: word_id - word statuses: word_id - status 在每个表中 word_
我是单元测试的新手,所以请对我宽容一些。我有一些查询 RESTful API 的模块。我发现在每个测试套件中,我都使用几行代码来启动一个简单的 ExpressJS Web 服务器,以模拟一些我可以从测
假设我有以下代码: var blinker = function(element){ if(stopped){ return; } else { var sampleMappi
我正在用 JavaScript 制作一个选择你自己的冒险风格的游戏,在本节中: evade = prompt("Go out of your way to avoid them, just in ca
我的代码: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Events1 extends
我正在使用 scipy ode 来解决钟摆问题。 from scipy import * import matplotlib.pyplot as plt from scipy.integrate im
我有一个 Google 表格,用于收集客户的注册数据。收集的数据包括学生的姓名、学生选择参加的类(class)以及信用卡号。提交后,我会收到通知。收到通知后,我会转到我的 Google 表格并从信用卡
我需要定义一个操作的两个版本,定义略有不同。它是一系列包含Nat指数的成分。 open import Data.Nat data Hom : ℕ → ℕ → Set where id : (
我正在研究游戏引擎 http://ducttape-dev.org使用 boost 作为依赖项之一。有一天,当我正在编写一个链接到我的游戏引擎的测试应用程序时,OgreProcedural 的 Ext
我正在 Android 中制作一个表达式计算器,所以我想在实际计算答案之前检查字符串是否符合有效表达式的条件。 我在 Java 中试过这个正则表达式: ^\s*([-+]?)(\d+)(?:\s*([
我有以下 postgresql 查询(为便于阅读而简化): select * from a_view where a in (select * from a_function(a_input))
我开始更好地掌握 PostgreSQL 索引,但我遇到了 OR 条件的问题,我不知道如何优化我的索引以加快查询速度。 我有 6 个条件,当单独运行时,它们的成本似乎很小。下面是修剪查询的示例,包括查询
有谁知道为什么下面的代码接受诸如123-123-1234这样的答案: [1-9]\\d{2}-[1-9]\\d{2}-\\d{4} 我想到了代码,它只接受先接受 2 个数字,再接受 2 个数字,然后再
在使用 Java 1.8u40 打开带有提示类型和附加的 StringConverter 的组合框时,我遇到了以下错误。这可以追溯到执行 FXML 的团队留下的示例字符串,与 Controller 中
在 MySQL 中,我有三个不同的数据库 - 我们将它们称为 A、B 和 C。 是否可以执行涉及所有三个数据库(A、B、C)中的表的事务? (所有数据库都在同一服务器上) 最佳答案 是的,你可以。这是
我是一名优秀的程序员,十分优秀!