Replace using regular expression

Go To StackoverFlow.com

1

I would like to make a function that break lines from a string.

eg.: "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]. It's not a problem if the first option came with new line.

2012-04-04 00:06
by m.rufca
So just to be clear (because it seems the current answers have overlooked this): you don't want a CRLF in front of the 1. - slugster 2012-04-04 00:15


4

Give this guy a shot

Input = Regex.Replace(Input, @"(?<!^)(\d+\.)", "\n$1")
2012-04-04 00:12
by Mike Park
Works perfectly! Thanks : - m.rufca 2012-04-04 01:14


2

Regex rgx = new Regex("(\\d+\\.\\s)");
String replaced = rgx.Replace(Input, Environment.NewLine + "$1");
2012-04-04 00:19
by Petr Újezdský


1

A bit shorter expression like this would work too:

Regex.Replace(Input, @"(?!^)\d+\.", "\n$0")
2012-04-04 00:33
by Qtax
Ads