Make a line break when identifying (number + string)

Viewed 100

I have the following words:

12"The world... 13The end 14"I have 16 years 15Kiss me

And I need to separate it like this:

12"The world...

13The end

14"I have 16 years

15Kiss me

To separate, I use (number + string) example (123xxx)

Any number that is concatenated with a string I need to break \n before.

I used the regex below, but it does not take into account the special symbol, and there will be several symbols in the text. And even select a number yourself

\d+\w+

enter image description here

I'm using this code in C#, and I just need to put a valid regex:

private void method()
{
    string text = "12\"The world... 13The end 14\"I have 16 years 15Kiss me";
    string ntext = Regex.Replace(text, @"\d+\w+", "\n");            
}

How can I make a regex that takes (number + string) and makes a line break?

2 Answers

You can use

Regex.Replace(text, @"\s+(?=\d+[^\s\d])", "\n")

See the regex demo.

Details

  • \s+ - one or more whitespace chars
  • (?=\d+[^\s\d]) - a positive lookahead that matches a location immediately followed with 1+ digits and then a digit other than a digit and whitespace.

See the C# demo:

var text = "12\"The world... 13The end 14\"I have 16 years 15Kiss me";
Console.WriteLine(Regex.Replace(text, @"\s+(?=\d+[^\s\d])", "\n"));

Output:

12"The world...
13The end
14"I have 16 years
15Kiss me

You can try the example below:

var matches = Regex.Matches(value, "[\\d]+((\\s+[^\\d]+)|(?<g2>[^\\d]+))").ToArray();
var result = string.Join("",matches.Select(x=> x.Index != 0 &&  x.Groups["g2"].Success? $"{System.Environment.NewLine}{x.Value}" : x.Value));

enter image description here

Related