我有一个foreach语句正在搜索名单,其中在一个字符串值;字符串>
。如果当前行被读取包含字符串,我想取代它,但有一些注意事项。
I have a foreach statement that is searching for a string value within a List<string>
. If the current line being read contains the string, I want to replace it, but with certain caveats.
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.
}
}
我试图让系统忽略的字符串,如果一个下划线( pceded的
)。否则,我希望它被替换(即使它是在该行的开始)。 shorthandValue
是$ P $_
I'm trying to get the system to ignore the string if the shorthandValue
is preceded by an underscore character ("_"
). Otherwise, I want it to be replaced (even if it is at the start of the line).
我是谁不这样做是否正确?
What am I not doing correctly?
更新
这是主要工作正常:
Regex.Replace(currentFile, "[^_]" + Regex.Escape(shorthandValue), replaceText);
然而,虽然它并忽略下划线,它它除去shorthandValue串之前的任何空间。因此,如果该行读取。这是一个test123,和test123被替换,我结束了这样的结果:
However, while it does ignore the underscore, it it removing any space before the shorthandValue string. So if the line read "This is a test123.", and the "test123" is replaced, I end up with this result:
这是aVALUEOFTHESHORTHAND。
"This is aVALUEOFTHESHORTHAND."
为什么空间被删除?
再次更新
我改变了正则表达式回到我的。(小于?!_)
,这是preserving空格
I changed the regex back to my (?<!_)
and it is preserving the spaces.
推荐答案
您正则表达式是正确的。的问题是,Regex.Replace返回一个新字符串
Your regex is correct. The problem is that Regex.Replace returns a new string.
正在忽略了返回的字符串。
You are ignoring the returned string.
相关推荐
最新文章