-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegexExtensions.cs
More file actions
54 lines (51 loc) · 2.05 KB
/
RegexExtensions.cs
File metadata and controls
54 lines (51 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CSharpExtensions.OpenSource
{
public static class RegexExtensions
{
public static string? GetGroupValueOrNull(this Regex regex, string source, int groupIndex = 1, bool checkEmpty = true) => GetGroupValue(regex, source, groupIndex, false, checkEmpty);
public static string GetGroupValueOrThrow(this Regex regex, string source, int groupIndex = 1, bool checkEmpty = true) => GetGroupValue(regex, source, groupIndex, true, checkEmpty)!;
public static string? GetGroupValue(this Regex regex, string source, int groupIndex = 1, bool throwOnNull = false, bool checkEmpty = true)
{
if (regex != null && !string.IsNullOrEmpty(source))
{
var match = regex.Match(source);
if (match.Success)
{
var group = match.Groups[groupIndex];
if (group.Success)
{
if (!checkEmpty || !string.IsNullOrEmpty(group.Value))
{
return group.Value;
}
}
}
}
if (throwOnNull)
{
throw new Exception($"failed to get the value of capturing group {groupIndex}, regex pattern: {regex}, source: {source}");
}
return null;
}
public static List<string> GetGroupValuesOrNull(this Regex regex, string source, int groupIndex = 1)
{
var list = new List<string>();
var matches = regex.Matches(source);
foreach (Match match in matches)
{
if (match.Success)
{
var group = match.Groups[groupIndex];
if (group.Success && !string.IsNullOrEmpty(group.Value))
{
list.Add(group.Value);
}
}
}
return list;
}
}
}