I want to write a code that checks if it matches to a regular expression then prints matched string.
I found other question Can I use regex expression in c# with switch case?, but IsMatch
method only returns boolean so I couldn't retrieve named group string.
var filepath = @"path/to/file.txt";
foreach (string line File.ReadLines(filepath))
{
switch (line)
{
case var s when new Regex(@"^(?<UserName>\w ) moved to (?<Position>\w )$").IsMatch(s):
// I have to know <UserName> and <Position> here.
break;
...
}
}
CodePudding user response:
First, I'd suggest moving the regex construction itself outside the switch block - both for readability and to allow it to be reused.
Then, instead of using IsMatch
, use the Match
to return a Match
, which you'd then check for success (potentially using a C# pattern match). For example:
using System.Text.RegularExpressions;
class Program
{
private static void Main()
{
RunTest("Jon moved to XYZ");
RunTest("Not a match");
}
private static readonly Regex UserMovementRegex = new Regex(@"^(?<UserName>\w ) moved to (?<Position>\w )$");
private static void RunTest(string line)
{
switch (line)
{
case string _ when UserMovementRegex.Match(line) is { Success: true } match:
Console.WriteLine($"UserName: {match.Groups["UserName"]}");
Console.WriteLine($"Position: {match.Groups["Position"]}");
break;
default:
Console.WriteLine("No match");
break;
}
}
}
The { Success: true } match
part has two purposes:
- It checks that the match is successful
- It captures the result in a new
match
variable that you can use in the body of thecase
label
CodePudding user response:
You can get the values with Groups:
var regex = new Regex(@"^(?<UserName>\w ) moved to (?<Position>\w )$");
var match = regex.Match(blobContent);
if (match.Success)
{
string userName= m.Groups["UserName"].Value;
string position= m.Groups["Position"].Value;
}