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

Time:11-15

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

CodePudding user response:

  • 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

CodePudding user response:

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
  • Related