views:

887

answers:

4

I need some help with regex. i want to get the string which has a delimiter in it between two specific words.

e.g. i need a regex which matches:

Statements1 start Statements2 ; Statements3 end fun;

There can be multiple occurences 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;

Thanks.

A: 
start ((Statements) ;)+ (Statements) end fun
leppie
This doesn't meet the capturing requirements
Gavin Miller
Yes, it does, the regex for were not asked...
leppie
Ok, it does not, the original question has been altered...
leppie
A pain when that happens isn't it!
Gavin Miller
A: 

Might be quicker to use

    string[] Strings = stringToSplit.Split(new char[] { ';' });
    if (Strings.Count() > 1)
    {
        // Do your stuff
    }
Lazarus
thanks, but i want only regex.
Archie
A: 

It sounds like what you want is as simple as:

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

This would return the groups you list.

P Daddy
You need non-greedy qualifiers on your *'s, or it will match the last "end", not the first.
Jesse Rusak
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.
P Daddy
+1  A: 

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!

Gavin Miller
yes, i'm familier with the ?: syntax. But i'm sorry to say that this regex is not working.
Archie