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

Hakan
Hakan used Ask the Experts™
on
Hello,

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;

$J_____dummy_part1_to_part2_sometext

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

Any help would be great!.
Thanks.
Comment
Watch Question

Do more with

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

Commented:
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;
}
else
{
    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

Author

Commented:
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;

$J_____dummy_part1_to_part2

Thank you again.
Top Expert 2014
Commented:
If you mean that the last part is optional, then you can use the following regex:
(?:^\$J_____dummy_(.*?)_to_(.*?)(_.*)?$)?

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