gpt4 book ai didi

c# - 如何使用正则表达式替换匹配项,前提是它前面没有给定字符?

转载 作者:行者123 更新时间:2023-11-30 14:34:15 25 4
gpt4 key购买 nike

我有一个 foreach 语句在 List<string> 中搜索字符串值.如果正在读取的当前行包含该字符串,我想替换它,但有一些注意事项。

foreach (string shorthandValue in shorthandFound)
{
if (currentLine.Contains(shorthandValue))
{
// This method creates the new string that will replace the old one.
string replaceText = CreateReplaceString(shorthandValue);
string pattern = @"(?<!_)" + shorthandValue;
Regex.Replace(currentLine, pattern, replaceText);
// currentline is the line being read by the StreamReader.
}
}

我试图让系统在 shorthandValue 时忽略字符串前面有一个下划线字符 ( "_" )。否则,我希望它被替换(即使它在行的开头)。

我做错了什么?

更新

这大部分工作正常:

Regex.Replace(currentFile, "[^_]" + Regex.Escape(shorthandValue), replaceText);

然而,虽然它确实忽略了下划线,但它删除了 shorthandValue 字符串之前的所有空格。因此,如果该行显示为“This is a test123.”,并且替换了“test123”,我将得到以下结果:

“这是一个 VALUEOFTHESHORTHAND。”

为什么要删除空间?

再次更新

我将正则表达式改回我的 (?<!_)它正在保留空间。

最佳答案

您的正则表达式是正确的。问题是 Regex.Replace 返回一个新字符串。

您忽略了返回的字符串。

关于c# - 如何使用正则表达式替换匹配项,前提是它前面没有给定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14344129/

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