简体   繁体   English

正则表达式匹配冒号

[英]Regular expression to match colon

I need to add an interface to an class in c# and need to match if has already been declared: 我需要在c#中向类添加接口,并且如果已经声明,则需要匹配:

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" 我已经将此“公共部分类(\\ w +)”转换为“公共部分类$ 1:IEntity”

Thanks. 谢谢。

If you only want to handle that specific type of format (ie "public partial class 'classname'"). 如果您只想处理该特定类型的格式(即“公共局部类'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: 哪里:

  • ^ means match from the beginning. ^表示从头开始匹配。
  • $ means match to the end. $表示匹配到末尾。
  • [^:]+ means any character not ':' [^:] +表示不是':'的任何字符

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 最好不要添加额外的: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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM