使用正则表达式替换

本文关键字:替换 正则表达式 | 更新日期: 2023-09-27 18:29:51

我想制作一个函数,从字符串中换行。

例如:"1."->"''n1."

这样我就可以写一个类似的代码

string Input = "1. First option";
Input += "2. Second option";
Input += "3. Third option";
Output = WriteMenu(Input);

得到一个像这样的字符串

"1. First option
'n2. Second option
'n3. Third option"

模式将始终为[number][dot][whites]。如果第一个选项带有新线路,这不是问题。

使用正则表达式替换

给这家伙一枪

Input = Regex.Replace(Input, @"(?<!^)('d+'.)", "'n$1")
Regex rgx = new Regex("(''d+''.''s)");
String replaced = rgx.Replace(Input, Environment.NewLine + "$1");

像这样短一点的表达式也可以:

Regex.Replace(Input, @"(?!^)'d+'.", "'n$0")