Re: RegEx problem
- From: jac <jac@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 28 Jun 2007 10:16:01 -0700
Thank you, it works nice and it was a very good description how to read a
regex.
"Jesse Houwing" wrote:
* jac wrote, On 28-6-2007 17:26:.
Hi,
I have problems with following code and don’t find the bug :
// Set [8,9,54]
ArrayList aArray = new ArrayList();
regStr = new Regex(@"\[(?:(\d+)[,]?)*(\d+)\]");
if(text != null && regStr.IsMatch(text))
{
Match m = regStr.Match(text);
GroupCollection groups = m.Groups;
number = 0;
for(int i=1;i < groups.Count;i++)
{
foreach(Capture c in groups[i].Captures)
{
aArray.Add(c.Value.ToString());
number++;
}
}
}
[8,9] : thats working in my aArray I have 8 and 9
[16,5] : OK I have 16 and 5
[16,34] : That is nok I have 3 items in my array 16 and 3 and 4
[16] : that’s is nok I have 2 items in my array 1 and 6
Why m.groups has 3 groups for [16,34]? The same for [16] why m.groups has 2
groups.
I think it must be the last part of my regex expression (\d+). This is one
group even if there are more numbers in it. How can I solve this?
Thanks in advance,
jac
\[(?<number>\d+)(?:,(?<number>\d+))*\]
should do the trick. Currently there are too many options as both the ,
as well as the whole first group are optional (which they're not).
The new expression reads
find a [
find a number (one or more digits)
optionally find a comma followed by a number
repeat optional group if possible
find a ]
both number are captured in the same named group, which makes it easier
to extract the values:
Match m = regStr.Match(text);
foreach (Capture c in m.Groups["number"].Captures)
{
aArray.Add(c.Value);
}
number = aArray.Count;
Optionally you could also do a string.Split with '[', ',' and ']' as
separator characters which would probably be faster as well. You can
instruct string.Split to ignore empty groups.
string[] results = "[16,23,1]".Split(new char[] { ',', '[', ']' },
StringSplitOptions.RemoveEmptyEntries);
int number = results.Length;
I'd prefer this solution over the regex one.
Jesse
- References:
- Re: RegEx problem
- From: Jesse Houwing
- Re: RegEx problem
- Prev by Date: Re: Creating an XML file in temporary memory
- Next by Date: Re: Reflection question
- Previous by thread: Re: RegEx problem
- Next by thread: using splitContainer in an MdiContainer?
- Index(es):
Relevant Pages
|