0

I want to get the string which has a delimiter in it, between two specific words, using a regex.

e.g. I need a regex which matches:

Statements1 start Statements2 ; Statements3 end fun;

There can be multiple occurrences of ' ; ' between 'start' and 'end'.

Statements are multiple words where (.*) can be used in the regex for a word.

But the regex should not match if there is no ' ; ' between the 'start' and 'end'.

Also, the 'end' should be the first 'end' encountered after 'start'

So, the regex should not match

Statements1 start Statements2 end Statements3 ; end fun

I want the matches as

  1. statements before 'start'
  2. keyword
  3. statements after 'start'

So, in this case it would be a group(for the 1st string since 2nd should not match) as:

  1. Statements1
  2. start
  3. Statements2 ; Statements3 end fun;

4 Answers 4

1

So the below regex will match your positive case and fail the negative case and place the results into group 1, 2, & 3.

(.*?) (start) ((?:(?:.*?) ;)+ (?:.*?) end fun)

In case you're unfamiliar with the (?:) syntax - they signify non-capturing parentheses. Check out Mastering Regular Expressions, it's a great reference for this topic!

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

1 Comment

yes, i'm familier with the ?: syntax. But i'm sorry to say that this regex is not working.
0
start ((Statements) ;)+ (Statements) end fun

2 Comments

This doesn't meet the capturing requirements
A pain when that happens isn't it!
0

Might be quicker to use

    string[] Strings = stringToSplit.Split(new char[] { ';' });
    if (Strings.Count() > 1)
    {
        // Do your stuff
    }

Comments

0

It sounds like what you want is as simple as:

(.*)(start)(.*;.*end.*)

This would return the groups you list.

2 Comments

You need non-greedy qualifiers on your *'s, or it will match the last "end", not the first.
You're absolutely correct, although substituting lazy *s causes it to group the final "fun;" with the next match. Not sure how much this matters.

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.