简体   繁体   中英

C# Regex - Match expression that does not start with a specific word

I have read similar questions but I can't get this to work. I want to use the regex for the Find-Replace Visual Studio tool that supports C# regular expressions.

I want to find (and replace with nothing) expressions such as:

System.Collections.Generic.List
System.Web.UI.WebControls.Button

And remove System.Collections.Generic. and System.Web.UI.WebControls to tidy my code up.

BUT I want the ability to add new words after 'System.' to the expression if I want to scale it. So I have created this:

(System\\.)?(Collections\\.)?(Generic\\.)?(Web\\.)?(UI\\.)?(WebControls\\.)?

However, this also changes using statements such as:

using System.Data.SqlClient;

Is there a way to alter my regular expression so that it does not include matches that start with the "using" keyword?

I have tried using:

(^?!using)(System\\.)?(Collections\\.)?(Generic\\.)?(Web\\.)?(UI\\.)?(WebControls\\.)?

but this does not work. Thanks!

using negative lookbehind, to assert match is not preceeded by using

(?<!^using )

However as all parts are optionnal it will match Collections. in

using System.Collection.Generic.List

Which may be not wanted, also many regex engine have a limitation lookbehinds can't have a variable length match.

The syntax you have will allow for partial matching. Try specifying that "using" must appear 0 times. ^(using){0}

If that doesn't work, you can do the following: 1.Find and replace "using system" with "usingsistem". 2. Find and replace system.whatever. 3. Find and replace "usingsistem" with "using system"

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.

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