How to apply Regex.Match for my string structure in C#

Hakan used Ask the Experts™

I'd like to parse part1 and part2 name from my below string structure with Regex.Match.

I don't know it can be appliable but my string is like below;


if it's not matching i'd like return string.empty for part1 and part2

Any help would be great!.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

You can either set part1 and part2 to string.Empty when it doesn't match, or use a regex which matches always.

First option:
var match = Regex.Match(input, @"^\$J_____dummy_(.*?)_to_(.*?)_sometext$");
string part1, part2;
if (match.Success)
    part1 = match.Groups[1].Value;
    part2 = match.Groups[2].Value;
    part1 = string.Empty;
    part2 = string.Empty;

Open in new window

Second option:
var match = Regex.Match(input, @"(?:^\$J_____dummy_(.*?)_to_(.*?)_sometext$)?");
string part1 = match.Groups[1].Value;
string part2 = match.Groups[2].Value;

Open in new window


Hi louisfr ,

I made a minor change and it worked as i would like:

            var match = Regex.Match(input, @"(?:^\$J_____dummy_(.*?)_to_(.*?)_(.*?)$)?");

 also i would like to ask you is there any chance to implement a code to this single line to scope a cases like below;


Thank you again.
Top Expert 2014
If you mean that the last part is optional, then you can use the following regex:

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial