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.
}
}
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?
UPDATE
This is working mostly correctly:
Regex.Replace(currentFile, "[^_]" + Regex.Escape(shorthandValue), replaceText);
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:
"This is aVALUEOFTHESHORTHAND."
Why is the space being removed?
UPDATE AGAIN
I changed the regex back to my (?<!_)
and it is preserving the spaces.