fawad
fawad

Reputation: 1353

break sentence with regular express in C#

I'm trying to break the following string:

1. This is first 2. This is 45. second 3. This is third

using regular expression:

question = Regex.Split(strText, @" [0-9]+\. ");

It comes out like:

1. This is first 
2. This is 
45. second 
3. This is third

Where as i want like:

1. This is first 
2. This is 45. second 
3. This is third

Actually I want to break string with numbers from 1. to 30. If any other digit comes in the sentence statement it should not be broken. How can I tackle this string to get the above result?

Upvotes: 1

Views: 224

Answers (1)

fardjad
fardjad

Reputation: 20414

try this:

Regex.Split(strText, @"\b([0-2]?[1-9]|30)\.");

Update

The regex is correct for matching numbers between 1 to 30 followed by a dot as delimiters, the problem is the Regex.Split() behavior. I think you can't get what you want with Regex.Split() in one step. Use Regex.Replace and String.Split():

question = Regex.Replace(strText, @"(\b([0-2]?[1-9]|30)\.)", System.Environment.NewLine + "$1").Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Demo: http://rextester.com/IVM84413

Upvotes: 1

Related Questions