I am attempting to use C# Regex.Replace to automate a manual job of formatting strings in one structure into another. While I am able to identify and replace one sub-string, I have been unable to find examples of how to match and replace the rest of the string. I was wondering if there is a simple way to do this.
我正在尝试使用c# Regex。替换以自动将一个结构中的字符串格式化为另一个结构中的字符串。虽然我能够识别和替换一个子字符串,但我一直无法找到如何匹配和替换其余字符串的示例。我想知道是否有一种简单的方法。
Say I have this search pattern that identifies the string to be transformed:
假设我有这个搜索模式,它标识要转换的字符串:
const string inputPattern1 = "SOC.\\d.\\d.\\d.PO \\d";
Is it possible to set up replacement rules for each of the parameters?
是否可以为每个参数设置替换规则?
Here is a visual example of what I mean. Notice in the example that the string has a structure, so it's not a simple case of "replace any instance of X with Y".
这是我的一个直观的例子。请注意,在这个示例中,字符串有一个结构,所以它不是“用Y替换任何X实例”的简单情况。
This is what I have so far, using a C# console program to work out the methodology.
这就是我到目前为止所使用的方法,使用c#控制台程序来制定方法。
private static void Main()
{
const string input1 = "SOC.6.1.1.PO 8";
const string inputPattern1 = "SOC.";
const string replacement1A = "SSHS-S0";
// output should be: "SS06-S1C1-08"
var output1 = Regex.Replace(input1, inputPattern1, replacement1A);
Console.WriteLine("Input1: {0}",input1);
Console.WriteLine("Output1: {0}", output1);
}
The result is:
其结果是:
Input1: SOC.6.1.1.PO 8
Output1: SSHS-S06.1.1.PO 8
1 个解决方案
#1
3
Use capturing group numbers in your replacement string:
在替换字符串中使用捕获组号:
var res = Regex.Replace(
"SOC.6.1.1.PO 8"
, @"SOC\.(\d)\.(\d)\.(\d)\.PO (\d)"
, "SS0$1-S$2C$3-0$4"
);
$1
through $4
represent the content of the input string matched by parenthesized groups.
$1到$4表示由括号括起来的组匹配的输入字符串的内容。
演示。
#1
3
Use capturing group numbers in your replacement string:
在替换字符串中使用捕获组号:
var res = Regex.Replace(
"SOC.6.1.1.PO 8"
, @"SOC\.(\d)\.(\d)\.(\d)\.PO (\d)"
, "SS0$1-S$2C$3-0$4"
);
$1
through $4
represent the content of the input string matched by parenthesized groups.
$1到$4表示由括号括起来的组匹配的输入字符串的内容。
演示。