我在一个应用程序中工作,系统管理员可以创建自定义字段并配置计算来解析这些字段中的值。这些计算结果保存为 CustomField 对象的字符串属性。我的任务是批量清理这些计算,主要集中于交换函数和连接运算符及其短路变化。我正在寻找使用 RegEx.Replace() 方法在 .NET C# 解决方案中解决此任务。
示例计算字符串(用户以 VB.NET 语法键入 calc):
IIF([FIELD1] = "This and that" AND [FIELD2] = "This or that", "Value 1",
IIF ([FIELD3] = "This and that" OR [FIELD4] = "This or that", "Value 2",
""))
任务要求:
以下是我作为起点的示例。我相信我通过使用“备用”| 使 IIF 函数模式正确。管道字符对该短语进行非此即彼的匹配,但我坚持如何设置 AND/OR 模式以排除字符串中包含的匹配的替换。
foreach (CustomFieldInfo customField in Session.ConfigurationManager.GetCustomFields(false))
{
string fieldCalcStr = customField.Calculation.Trim();
if (string.IsNullOrEmpty(fieldCalcStr)) continue;
fieldCalcStr = Regex.Replace(fieldCalcStr, @"IIF\(|IIF *\(", "IF(", RegexOptions.IgnoreCase);
fieldCalcStr = Regex.Replace(fieldCalcStr, " AND ", " AndAlso ", RegexOptions.IgnoreCase);
fieldCalcStr = Regex.Replace(fieldCalcStr, " OR ", " OrElse ", RegexOptions.IgnoreCase);
customField.Calculation = fieldCalcStr;
}
注意:我在这里看到了各种各样的帖子,人们试图完成相对相似的事情,但在所有情况下,答案都是针对OP提供的输入字符串的,并且做出了假设,使得建议的答案不适用根据我的用户案例和具体要求。
非常感谢任何帮助。
您可以创建一个正则表达式,它将匹配引号内的字符串或搜索词(即
or
、and
等)。下面是不区分大小写的 and
示例,因此它匹配字符串(引号内)或 and
运算符,并且仅在匹配为 and
运算符 时才进行替换
var result = Regex.Replace(s, "(?i)\"(?:[^\"]+\\band\\b[^\"]+\")|(and)",
m =>
{
// group 1 contains only `and` operators which aren't inside within
if (m.Groups[1].Success)
{
return "AndAlso";
}
return m.Value;
});