Obtaining numbers from a string..

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Obtaining numbers from a string..

Post 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 :)
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

If ':' is always present, this

Code: Select all

/\d+(?=.*:)/
will extract all numbers that occur before ':'
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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 :)
Post Reply