简体   繁体   中英

Regular expression to take 2 parts of a string in c#

dir1\\dir2\\dir3\\file.aspx.cs (343,49): error CS0839: Argument missing [ C:\\dir\\dir\\dir\\dir\\namespace.namespace.namespace.namespace\\ project.csproj]

I've been trying for hours to create a regular expression to extract just 2 areas of this string. The bold areas are the parts I wish to capture.

I need to split this string into two seperate strings:

  1. I'd like everything before the first "("
  2. everything between the "[" and "]" but not including the "project.csproj"

For #1 the closest i've gotten is (^.*\\() which will basically capture everything up to the first "(" ( including the bracket though which I don't want )

For #2 the closest i've gotten is (\\[.*\\]) which will basically capture everything inside the brackets ( including the brackets which i don't want ).

Any of the words in the above string could change apart from ".csproj" "C:\\" and ".cs"

Context: This is how MSBuild spits errors out when compiling. By capturing these two parts I can concatenate them to provide an exact link to the erroring file and open the file in Visual Studio automatically:

System.Diagnostics.Process.Start("devenv.exe","/edit path");

This pattern:

(^[^(]*).*\[(.*)project.csproj]$

Captures these groups:

  1. dir1\\dir2\\dir3\\file.aspx.cs
  2. C:\\dir\\dir\\dir\\dir\\namespace.namespace.namespace.namespace\\

If the name project.csproj file could change, you can use this pattern instead:

(^[^(]*).*\[(.*\\)[^\\]*]$

This will match everything up to the last path fragment within the brackets.

Well, right now the parentheses aren't doing you any good. Just place them around the parts you are interested in:

^(.*)\(

and

\[(.*)\]

Now to exclude projects.csproj from the match, simply include it after the .* :

\[(.*)projects.csproj\]

Then match.Groups(1) will give you the desired string in each case (where match is your Match object).

If projects.csproj can be any file name (ie you only want everything until the last backslash, use:

\[(.*?)[^\\]*\]

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