Page 1 of 1

Obtaining numbers from a string..

Posted: Fri May 11, 2007 6:16 am
by Jenk
A bit more complex than the title suggests..

sample data:

Code: Select all

bug 235, bug 321: Merge into trunk for branches.
Bug 1208 : Merged changes into Trunk.
Bug 1151 : Merged Changes into Trunk.
Bug 1210 : Merged Changes into Trunk.
Bug 1205 : Merged changes into Trunk.
Bug 1192 : Merged changes into Trunk
bug 345, bug 346, bug 1007 : merged changes into trunk for version 1.22.01002
I'm trying to extract the bug numbers - and store them in a flat array.
so far:

Code: Select all

$bugs = array();
foreach($data as $line)
{
    if (preg_match('/(?:(?:bug ([0-9]+)+[,\s]*?)+:.*merge.*trunk)/i', $line))
    {
        preg_match_all('/[0-9]+/', $line, $matches);
        foreach ($matches as $match)
        {
            if (is_array($match)) 
            { 
                foreach ($match as $m) $bugs[] = $m;
            }
            else 
            {
                $bugs[] = $match;
            }
        }
    }
}
but of course that is also pulling and storing the numbers from the comment string (everything past the ':' is to be disregarded)
I've got coders block with it at the moment, so if anyone could be so kind as to help, I'll be much obliged :)

Posted: Fri May 11, 2007 6:41 am
by stereofrog
If ':' is always present, this

Code: Select all

/\d+(?=.*:)/
will extract all numbers that occur before ':'

Posted: Fri May 11, 2007 7:21 am
by Jenk
I don't think that works for examples like the first line and last line of my example data, does it?

EDIT: just tried it out, it works very well, thanks :)