Regex guru help please...

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

We have a bunch of strings in the following format:

[xxxxx] yyyy [xxxxx] yyyyy

We would like to keep all of the "xxxxx" data - anything that falls within
the square brackets. We know that Regex can do this but, whooaa - how do you
make it do this?
 
Richard said:
Hi,

We have a bunch of strings in the following format:

[xxxxx] yyyy [xxxxx] yyyyy

We would like to keep all of the "xxxxx" data - anything that falls within
the square brackets. We know that Regex can do this but, whooaa - how do
you
make it do this?

Regex regex = new Regex(@"\[([^\]]+)\]");
Match m = regex.Match(YOUR_TEXT);
StringCollection stringCollection = new StringCollection();

while (m.Success)
{
stringCollection.Add(m.Groups[1].Captures[0].Value);
m = m.NextMatch();
}
 
Thanx alot! Is there any way I can have it not return the square braces in
the result?

PW said:
Richard said:
Hi,

We have a bunch of strings in the following format:

[xxxxx] yyyy [xxxxx] yyyyy

We would like to keep all of the "xxxxx" data - anything that falls within
the square brackets. We know that Regex can do this but, whooaa - how do
you
make it do this?

Regex regex = new Regex(@"\[([^\]]+)\]");
Match m = regex.Match(YOUR_TEXT);
StringCollection stringCollection = new StringCollection();

while (m.Success)
{
stringCollection.Add(m.Groups[1].Captures[0].Value);
m = m.NextMatch();
}
 
Richard said:
We have a bunch of strings in the following format:

[xxxxx] yyyy [xxxxx] yyyyy

We would like to keep all of the "xxxxx" data - anything that falls within
the square brackets. We know that Regex can do this but, whooaa - how do
you
make it do this?

In addition to PW's suggestion, you can also get the modified string back
from a regex replacement in one go. Just call Regex.Replace to replace this:

(?<!\[[^\]]*)[^\[\]]*(?![^\[]*\])

by nothing (just pass in an empty string for the replacement parameter. It
should return

[xxxxx][xxxxx]

for your sample above.

If you want to get rid of the brackets themselves as well, use this
expression instead:

\]?(?<!\[[^\]]*)[^\[\]]*(?![^\[]*\])\[?

This will give the result

xxxxxxxxxx

for your sample.

Looks a bit like line noise, doesn't it? :-)


Oliver Sturm
 
Back
Top