简体   繁体   English

使用正则表达式替换

[英]Replace using regular expression

I would like to make a function that break lines from a string.我想制作一个 function 从字符串中换行。

eg.: "1. " -> "\n1. "例如:“1.” -> “\n1.”

so i could write a code like this所以我可以写这样的代码

string Input = "1. First option";
Input += "2. Second option";
Input += "3. Third option";

Output = WriteMenu(Input);

and get a string like this得到这样的字符串

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

The pattern will always be [number][dot][whitespace].模式将始终是 [number][dot][whitespace]。 It's not a problem if the first option came with new line.如果第一个选项带有换行,这不是问题。

Give this guy a shot给这家伙一个机会

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

A bit shorter expression like this would work too:像这样更短的表达式也可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM