Home > other >  C# REGEX: I need to find all occurences of ".FullName" and replace with ".Name"
C# REGEX: I need to find all occurences of ".FullName" and replace with ".Name"

Time:10-09

Using REGEX, how do I find all the occurrences of ".FullName" where "Log" is also used? I want to change ".FullName" to ".Name". I want to ignore any occurrence of ".FullName" where "Log" does not appear. (There is no guarantee each line will start with "Log.Write" or "GetType()". Thus I'm only looking for ".FullName" where "Log" is also used.)

Here is some sample text:

Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Trace, "Closing form {0}", Thread.CurrentThread);

Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Trace, "ID Scanner Message Received: {0}", (int)m.WParam);

validParentDirectories.Add(new DirectoryInfo(Path.Combine(currentDirectory.FullName, subDir)));

var fileLocation = new FileInfo(Path.Combine(currentDirectory.FullName, zipEntry.FileName));

if (!validParentDirectories.Any(vpd => fileLocation.DirectoryName.StartsWith(vpd.FullName, StringComparison.InvariantCultureIgnoreCase)))

Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Error, ex);

CodePudding user response:

You can replace .FullName in lines where the word Log previously appeared like this:

string input = @"
Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Trace, ""Closing form {0}"", Thread.CurrentThread);
Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Trace, ""ID Scanner Message Received: {0}"", (int)m.WParam);

validParentDirectories.Add(new DirectoryInfo(Path.Combine(currentDirectory.FullName, subDir)));

var fileLocation = new FileInfo(Path.Combine(currentDirectory.FullName, zipEntry.FileName));

if (!validParentDirectories.Any(vpd => fileLocation.DirectoryName.StartsWith(vpd.FullName, StringComparison.InvariantCultureIgnoreCase)))
    Log.Write(GetType().FullName, MethodBase.GetCurrentMethod().Name, LogEntryType.Error, ex);";

string replaced = Regex.Replace(input, @"(?m)(?<=^.*Log.*\.)FullName\b", "Name");

The regex pattern works as follows:

  • (?m) - Use multi-line mode, ^ and $ match the start and end of individual lines
  • (?<=^.*Log.*\.) - Assert that the current position is preceded by start of a line, optionally more characters, the word Log, and a literal dot
  • FullName\b - match the literal word FullName followed by a word boundary

CodePudding user response:

If you expect the log to be anywhere in the line, a C# regex for that would be

@"(?<=Log.*?\.)Full(?=Name)|(?<=\.)Full(?=Name.*?Log)"

https://regex101.com/r/M13sHQ/1

Replace with nothing.

   (?<= Log .*? \. )
   Full
   (?= Name )
 | 
   (?<= \. )
   Full
   (?= Name .*? Log )
  • Related