user20465780
user20465780

Reputation: 35

How to split a text by words instead of .?! marks using Regex Split?

I want to split a text by different words and not by periods. Here is a code I tried:

string StringFromTheInput = TextBox1.Text;
string[] splichar1 = Regex.Split(StringFromTheInput, @"(?<=[\because\and\now\this is])");

I want to use these words or phrases as delimiter in text instead of period mark, this is an example what output I need:

 Text: Sentence blah blah blahh because bblahhh balh and blahhh
 Output: because bblahhh balh and blahhh

 another example-

Text: bla now blahhh

Output: now blahhh

Upvotes: 0

Views: 180

Answers (2)

Yiyi You
Yiyi You

Reputation: 18209

You can try to find the position of \because\and\now\this is,and then use substring.

string StringFromTheInput = TextBox1.Text;
 string str="";
            var match = Regex.Match(s, @"\b(because|and|now|this is)\b");
            if (match.Success)
            {
                var index=match.Index; // 25
                str = s.Substring(index);//str is what you want
            }

Output:

because bblahhh balh and blahhh

Upvotes: 1

Zakaria Najim
Zakaria Najim

Reputation: 68

  • You can do it with String.Contains Method and String.Substring Method.

Code:

string stringfromtheinput = "Sentence blah blah blahh because bblahhh balh and blahhh";
String[] spearator = {
  "because",
  "and",
  "now",
  "this is"
};

foreach(string x in spearator) {
  if (stringfromtheinput.Contains(x)) {
    Console.WriteLine(stringfromtheinput.Substring(stringfromtheinput.LastIndexOf(x)));
  }
}

Output:

because bblahhh balh and blahhh
and blahhh

Upvotes: 2

Related Questions