Regular expression problem with repetition of matches

  • Thread starter Thread starter Billy_270
  • Start date Start date
B

Billy_270

Hi!
I have a text "*.jpg;*.bmp;*.png" and I'd like to get "*.jpg", "*.bmp" and
"*.png". I've tried the pattern "^(?:(\*\..+);)*(\*\..+)$", but it doen't
work because it returns "*.jpg;*.bmp" and "*.png" (I know, it returns the
longest sequence).
Is there a pattern that would return what I want (instead of storing the
second match and recursively getting the first match, re-applying the
pattern until only one match is returned)?
 
You can use the following expression:

^(?:(\*\..+?)(?:;|$))*

The values will be in the Captures collection of Group number 1.

So if you have the match stored in the variable m:

m.Groups[1].Captures[0].Value = "*.jpg"
m.Groups[1].Captures[1].Value = "*.bmp"
m.Groups[1].Captures[2].Value = "*.png"


Brian Davis
www.knowdotnet.com
 
you can also use non-greedy matching by adding ? after the *


--
Eric Newton
C#/ASP Application Developer
(e-mail address removed)-software.com [remove the first "CC."]

Brian Davis said:
You can use the following expression:

^(?:(\*\..+?)(?:;|$))*

The values will be in the Captures collection of Group number 1.

So if you have the match stored in the variable m:

m.Groups[1].Captures[0].Value = "*.jpg"
m.Groups[1].Captures[1].Value = "*.bmp"
m.Groups[1].Captures[2].Value = "*.png"


Brian Davis
www.knowdotnet.com


Billy_270 said:
Hi!
I have a text "*.jpg;*.bmp;*.png" and I'd like to get "*.jpg", "*.bmp" and
"*.png". I've tried the pattern "^(?:(\*\..+);)*(\*\..+)$", but it doen't
work because it returns "*.jpg;*.bmp" and "*.png" (I know, it returns the
longest sequence).
Is there a pattern that would return what I want (instead of storing the
second match and recursively getting the first match, re-applying the
pattern until only one match is returned)?
 
Back
Top