Wednesday 4 July 2012

Match string between same delimiters multiple times

Been looking for something like this for a while...

I had a string similar to below:

"thisis%a%%test%string%which%should%will%possibly%work%"

and needed to extract the text between the "%"'s, but not between the end "%" and the next starting "%".

Using regular expressions (in powershell), the following pattern will work:

"%[^%]*?(|).*?%"

The "?" after each "*" allows for greediness(multiple text blocks in the string)

Complete code:


[regex]$r = "%[^%]*?(|).*?%"
$r.Matches("thisis%a%%test%string%which%should%will%possibly%work%") | %{$_.Value}




The following is matched:
%a%
%test%
%which%
%will%
%work%
While the following is ignored:
%string%
%should%
%possibly%

No comments:

Post a Comment