1

heres is the code where I get strings from a textbox:

string txtS = TextBoxS.Text;

than extract some text with regex:

string[] splitS=Regex.Split(txtS, @"\s(we|tomorow)\s");

text: Today we have a rainy day but maybe tomorow will be sunny.

Now after splitting this gives me an output within a splitting point OutPut: have a rainy day but maybe

But what regular expression to use to get an output including the splitting points or delimiters, so I want this output: we have a rainy day but maybe tomorow I tried some other regular epressions but didn`t find the proper one....

6
  • Try to match and extract the value of the group with \s(we.+tomorow)\s. See the example in the regex tool here: regex101.com/r/ZVBnZQ/1 Commented Nov 18, 2022 at 20:53
  • I tried it adding points or plus sign but didn`t work... Commented Nov 18, 2022 at 20:55
  • Would it be possible that tomorrow and we appear in a different order or even multiple times? What would you expect then? Commented Nov 18, 2022 at 20:57
  • Try the example in the regex tool it works. I tried to execute the generated C# code and the console displays the correct answer expected in your post. You have to MATCH and not SPLIT with that regex. However if the order of WE or TOMOROW is different then the regex would not obviously be the same. Commented Nov 18, 2022 at 21:02
  • different order is okay so how would I extract: "we have a rainy day but maybe " only? Commented Nov 18, 2022 at 21:32

1 Answer 1

0

The C# code would be :

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\s(we.+tomorow)\s";
        string input = @"Today we have a rainy day but maybe tomorow will be sunny.";
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("{0}", m.Value);
        }

        Console.ReadKey();
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

the problem is that I use words as delimiter too where I only extract the text without delimiters and I need the other part where I include the delimiters too... so need both of them combined?
Yes, if you use Regex.Split() you should store the results in another array or list variable and add (meaning prepend and append) the delimiters. If you use Regex.Matches() you'll probably have the delimiters among the matched results like shown in my answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.