regex - How to delete first text? (c#)


Keywords:c# 


Question: 

I want to code

var text = "14. hello my friends we meet 1 test, 2 baby 3 wiki 4 marvel";
string[] split = text.Split('14.', 1, 2, 3, 4);
var needText = split[0].Replace('14.', '');

"1" "2" "3" "4" is static text.

but, "14." is dynamic text.

ex)

var text2 = "1972. google youtube. 1 phone, 2 star 3 tv 4 mouse";
string[] split = text.Split('1972.', 1, 2, 3, 4);
var needText = split[0].Replace('1972.', '');

2 Answers: 

If you have dynamic separators like this, String.Split is not suitable. Use Regex.Split instead.

You can give a pattern to Regex.Split and it will treat every substring that matches the pattern as a separator.

In this case, you need a pattern like this:

\d+\. |1|2|3|4

| are or operators. \d matches any digit character. + means match between 1 to unlimited times. \. matches the dot literally because . has special meaning in regex.

Usage:

var split = Regex.Split(text, "\\d+\\. |1|2|3|4");

And I think the text you need is at index 1 of split.

Remember to add a using directive to System.Text.RegularExpressions!

 

If you use IndexOf() with Substring(), you can very easily grab the information you need. If it's any more complex than your examples then use Regex.

var text = "14. hello my friends we meet 1 test, 2 baby 3 wiki 4 marvel";
var strArr = text.Substring(text.IndexOf(' ')).Split('1', '2', '3', '4');