gpt4 book ai didi

c# - 字符串操作 : How to replace a string with a specific pattern

转载 作者:太空狗 更新时间:2023-10-30 01:21:10 25 4
gpt4 key购买 nike

我这里有一个与基于特定模式的字符串操作相关的问题。我正在尝试使用 C# 将特定模式替换为预定义模式

例如:

场景#1

Input: substringof('xxxx', [Property2])
Output: [Property2].Contains('xxxx')

这个字符串可以在 linq 的 Where 子句中使用。

我的解决方案:

var key= myString.Substring(myString.Split(',')[0].Length + 1, myString.Length - myString.Split(',')[0].Length - 2);
var value = myString.Replace("," + key, "").Replace([Key from Dictionary], [Value from Dictionary]);

Expected string: key + '.' + value.Replace("('", "(\"").Replace("')", "\")");

但这只适用于上述场景。我想将其概括为以下所有场景。

场景:

Input: [Property1] == 1234 and substringof('xxxx', [Property2]) and substringof('xxxx', [Property3])
Output: [Property1] == 1234 and [Property2].Contains('xxxx') and [Property3].Contains('xxxx')

Input: substringof('xxxx', [Property2]) and [Property1] == 1234 and substringof('xxxx', [Property3])
Output: [Property2].Contains('xxxx') and [Property1] == 1234 and [Property3].Contains('xxxx')

如有任何帮助,我们将不胜感激。提前致谢!!

最终解决方案:

var replaceRegex = new Regex("substringof\\(\\s*'(?<text>[^']*)'\\s*,\\s*(?<pname>[\\w\\[\\]]+)\\s*\\)");
input = replaceRegex.Replace(input, "${pname}.Contains(\"${text}\")");

最佳答案

下面是一些似乎有效的示例代码:

System.Text.RegularExpressions.Regex replaceRegex = new System.Text.RegularExpressions.Regex("substringof\\(\\s*'(?<text>[^']*)'\\s*,\\s*(?<pname>[\\w\\[\\]]+)\\s*\\)");

string input1 = "[Property1] == 1234 and substringof('xxxx', [Property2]) and substringof('xx xx', [Property3])";
string input2 = "substringof('xxxx', [Property2]) and [Property1] == 1234 and substringof('xxxx', [Property3])";
string input3 = "(Id > 0 and substringof('2', Name))";

string output1 = replaceRegex.Replace(input1, "${pname}.Contains('${text}')");
string output2 = replaceRegex.Replace(input2, "${pname}.Contains('${text}')");
string output3 = replaceRegex.Replace(input3, "${pname}.Contains('${text}')");

请注意,我添加了对某些内部空格的容忍度,并对要匹配的文本做出了假设。引号和/或属性标识符中可以包含哪些字符?这可能需要进行调整以满足这些要求。

编辑:我做了一些主动调整。将\w* 更改为 [^']* 意味着它将匹配空格或符号或其他任何内容,直到它到达结束引号,然后停止匹配。这更符合标准的编程语言。属性名称保持更严格的限制:\w 将匹配字母、数字和下划线字符。这些都不能替代适当的解析器/词法分析器来捕获错误并明确识别它们,但在紧要关头它可能会起作用。

编辑 2:更新以删除对括号的要求。请注意,这是非常宽容的:该模式将匹配奇怪的字符串,如 substringof('xxxx', [[Property3]morestuffhere[) 因为它只是假定 [ 和 ] 是您标识符中的有效字符。无论是否有括号,它都不允许使用符号或空格。 请注意,替换字符串也发生了变化。如果您不删除方括号(正如我在示例中所做的那样),您最终可能会得到双括号。

关于c# - 字符串操作 : How to replace a string with a specific pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16464300/

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