Skip to content

Commit e24d3d4

Browse files
committed
🎨 Match char Span
1 parent f8d9231 commit e24d3d4

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/BD.Common8.Bcl/Extensions/MatchExtensions.cs

+60
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,64 @@ public static IEnumerable<string> GetValues(this MatchCollection match, Func<Mat
2828
if (action.Invoke(item))
2929
yield return item.Value.Trim();
3030
}
31+
32+
/// <summary>
33+
/// 获取正则表达式匹配的单个字符串值
34+
/// </summary>
35+
/// <param name="regex"></param>
36+
/// <param name="input"></param>
37+
/// <param name="defaultValue"></param>
38+
/// <returns></returns>
39+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
40+
[return: NotNullIfNotNull(nameof(defaultValue))]
41+
public static string? GetValue(
42+
this Regex regex,
43+
ReadOnlySpan<char> input,
44+
string? defaultValue = "")
45+
{
46+
#if DEBUG
47+
var a = regex.Match(new string(input));
48+
var b = a.GetValue(it => it.Success);
49+
#endif
50+
51+
foreach (var it in regex.EnumerateMatches(input))
52+
{
53+
if (input.IsEmpty)
54+
{
55+
break;
56+
}
57+
var val = input.Slice(it.Index, it.Length).Trim();
58+
if (val.EndsWith(Environment.NewLine))
59+
{
60+
val = val[..^Environment.NewLine.Length];
61+
}
62+
val = val.Trim();
63+
return new(val);
64+
}
65+
return defaultValue;
66+
}
67+
68+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
69+
[return: NotNullIfNotNull(nameof(defaultValue))]
70+
public static string? GetJoinValue(
71+
this Regex regex,
72+
ReadOnlySpan<char> input,
73+
char separator,
74+
string? defaultValue = "")
75+
{
76+
List<string> list = new();
77+
foreach (var it in regex.EnumerateMatches(input))
78+
{
79+
if (input.IsEmpty)
80+
{
81+
break;
82+
}
83+
list.Add(new(input.Slice(it.Index, it.Length)));
84+
}
85+
if (list.Count != 0)
86+
{
87+
return string.Join(separator, list);
88+
}
89+
return defaultValue;
90+
}
3191
}

0 commit comments

Comments
 (0)