Regex Replacing only whole matches

Posted by Leen Balsters on Stack Overflow See other posts from Stack Overflow or by Leen Balsters
Published on 2012-11-24T20:05:53Z Indexed on 2012/11/25 11:04 UTC
Read the original article Hit count: 184

Filed under:
|

I am trying to replace a bunch of strings in files. The strings are stored in a datatable along with the new string value.

string contents = File.ReadAllText(file);
foreach (DataRow dr in FolderRenames.Rows)
{
    contents = Regex.Replace(contents, dr["find"].ToString(), dr["replace"].ToString());

    File.SetAttributes(file, FileAttributes.Normal);

    File.WriteAllText(file, contents);
}

The strings look like this _-uUa, -_uU, _-Ha etc.

The problem that I am having is when for example this string "_uU" will also overwrite "_-uUa" so the replacement would look like "newvaluea"

Is there a way to tell regex to look at the next character after the found string and make sure it is not an alphanumeric character?

I hope it is clear what I am trying to do here. Here is some sample data:

private function _-0iX(arg1:flash.events.Event):void
    {
        if (arg1.type == flash.events.Event.RESIZE) 
        {
            if (this._-2GU) 
            {
                this._-yu(this._-2GU);
            }
        }
        return;
    }

The next characters could be ;, (, ), dot, comma, space, :, etc.

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex