Link to home
Start Free TrialLog in
Avatar of Skale
Skale

asked on

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

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.
Avatar of louisfr
louisfr

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

Avatar of Skale

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of louisfr
louisfr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial