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.
Regular ExpressionsC#

Avatar of undefined
Last Comment
louisfr
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
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

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo