user2619395
user2619395

Reputation: 249

String Equal to Regex Result?

I have a regex result I would like to capture in order to use it throughout my code. Such as, i'm using regex to get rid of a specific part in a string and i'd like to capture the result in string variable.

Is it even possible to do such a thing? And how does one even go about it?

Input:

C:\Users\Documents\Development\testing\11.0.25.10\W_11052_0_X.pts

Expected Result that I want to store into a string:

C:\Users\Documents\Development\testing\11.0.25.10\

Regex Pattern: ^(.*[\\])

Upvotes: 1

Views: 113

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

Of course you can: Groups property of the System.Text.RegularExpressions.Match object lets you access the match in the form of a string by accessing the Value property of the corresponding group.

For example, you can do this to capture the value of the expected output from your example:

string nameString = @"C:\Users\Documents\Development\testing\11.0.25.10\W_11052_0_X.pts";
// Note that I needed to double the slashes in your pattern to avoid the "unmatched [" error
string pathPrefix = Regex.Match(nameString, @"^(.*[\\])").Groups[1].Value;
Console.WriteLine(pathPrefix);

The above prints

C:\Users\Documents\Development\testing\11.0.25.10\

Here is a demo on ideone.

Upvotes: 2

Related Questions