不清楚(从原始问题)你想对数字做什么;让我们提取一个 自定义方法 供您实现。例如,我实现了 reverse:
32 -> 32
32-36 -> 36-32
36-32-37 -> 37-32-36
36-37-38-39 -> 39-38-37-36
代码:
// items: array of digits codes, e.g. {"36", "32", "37"}
//TODO: put desired transformation here
private static IEnumerable<string> Transform(string[] items) {
// Either terse Linq:
// return items.Reverse();
// Or good old for loop:
string[] result = new string[items.Length];
for (int i = 0; i < items.Length; ++i)
result[i] = items[items.Length - i - 1];
return result;
}
现在我们可以使用正则表达式 (Regex) 来提取所有数字序列并用转换后的序列替换它们:
using System.Text.RegularExpressions;
...
string input = "E5-20-36-32-37-20-E0";
string result = Regex
.Replace(input,
@"(?<=20\-)3[0-9](\-3[0-9])*(?=\-20)",
match => string.Join("-", Transform(match.Value.Split('-'))));
Console.Write($"Before: {input}{Environment.NewLine}After: {result}";);
结果:
Before: E5-20-36-32-37-20-E0
After: E5-20-37-32-36-20-E0
编辑:如果 reverse 是唯一需要的转换,则可以通过删除 Transform 并添加 Linq 来简化代码:
using System.Linq;
using System.Text.RegularExpressions;
...
string input = "E5-20-36-32-37-20-E0";
string result = Regex
.Replace(input,
@"(?<=20\-)3[0-9](\-3[0-9])*(?=\-20)",
match => string.Join("-", match.Value.Split('-').Reverse()));
更多测试:
private static string MySolution(string input) {
return Regex
.Replace(input,
@"(?<=20\-)3[0-9](\-3[0-9])*(?=\-20)",
match => string.Join("-", Transform(match.Value.Split('-'))));
}
...
string[] tests = new string[] {
"E5-20-32-36-20-E0",
"E5-20-37-20-E9",
"E5-20-37-38-39-20-E9",
"E5-20-38-39-20-E7-E4-20-37-35-20-E9",
};
string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-37} -> {MySolution(test)}"));
Console.Write(report);
结果:
E5-20-32-36-20-E0 -> E5-20-36-32-20-E0
E5-20-37-20-E9 -> E5-20-37-20-E9
E5-20-37-38-39-20-E9 -> E5-20-39-38-37-20-E9
E5-20-38-39-20-E7-E4-20-37-35-20-E9 -> E5-20-39-38-20-E7-E4-20-35-37-20-E9
编辑 2: 正则表达式解释(详见https://www.regular-expressions.info/lookaround.html):
(?<=20\-) - must appear before the match: "20-" ("-" escaped with "\")
3[0-9](\-3[0-9])* - match itself (what we are replacing in Regex.Replace)
(?=\-20) - must appear after the match "-20" ("-" escaped with "\")
我们来看看比赛部分3[0-9](\-3[0-9])*:
3 - just "3"
[0-9] - character (digit) within 0-9 range
(\-3[0-9])* - followed by zero or more - "*" - groups of "-3[0-9]"