I need to add an interface to an class in c# and need to match if has already been declared:
public partial class Client
Needs to be
public partial class Client: IEntity
When the occurrence already exists
public partial class Client: IEntity
Must remain
I have reached this "public partial class (\\w+)" into "public partial class $1: IEntity"
Thanks.
If you only want to handle that specific type of format (ie "public partial class 'classname'"). Something like this would do it:
class Program
{
static readonly Regex re = new Regex( @"^public partial class[^:]+$", RegexOptions.Compiled );
static string Replacement( string stringToReplace )
{
return re.Replace( stringToReplace, match => match.Value + ": IEntity" );
}
static void Main()
{
string newString = Replacement( "public partial class Client" );
Console.WriteLine( newString ); //output: "public partial class Client: IEntity"
newString = Replacement( "public partial class Server" );
Console.WriteLine( newString ); //output: "public partial class Server: IEntity"
newString = Replacement( "public partial class Server: IEntity" );
Console.WriteLine( newString ); //output: "public partial class Server: IEntity"
}
}
Where:
I'd say a straight up regex is a dangerous approach.
What if you have:
public partial class Client: RichClient
better be sure not to add an extra : IEntity
If it is possible you could maybe get the complete line text and then write a function to determine what to do.
Could there be a problem with spanning multiple lines?
看来您正在寻找这样的东西
(get-content test.cs -raw) -replace 'public partial class (\w+)(:.*)?$','public partial class $1: IEntity'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.