tags:

views:

74

answers:

2

Hi all,

Please could someone help me, i will be forever appreciative.

I'm trying to create a regular expression which will extract 797 from "Your job 797 ("job_name") has been submitted"

or "Your Job 9212 ("another_job_name") has been submitted" etc.

Any ideas? Thanks guys!

+2  A: 

If the rest of the string is guaranteed to be same, a simple \d+ would suffice.

Otherwise, use Your job (\d+) and read the first captured group.

preg_match("/Your job (\d+)/", $str, $matches);
echo $matches[1]; //prints the id.

Edit: modified to get job name

preg_match("/Your job (\d+) \("(.+?)"\)/", $str, $matches);
echo $matches[1]; //prints the id.
echo $matches[2]; //prints the job name.
Amarghosh
Thank you ! :-)
Jamie
+2  A: 

Are there any special conditions about grabbing the number?

To grab the first number, just use /\d+/ with preg_match.

if (preg_match('/\d+/', $subject, $match)) {
    $job_id = (int) $match[0];
}

Otherwise you could do something like the following which searches for a number preceeded by "job" (case-insensitive).

if (preg_match('/job (\d+)/i', $subject, $match)) {
    $job_id = (int) $match[1];
}

(There are better alternatves for this regex, but best to keep things simple at first.)


Another option would be to move away from regular expressions into more basic parsing of a string:

sscanf($subject, 'Your Job %d ("%[^"]")', $job_id, $job_title);
// use $job_id and $job_title however you like

Of course, similar could be done with preg_match but it's good to offer alternatives.

salathe
Excellent answer, thank you! :-)Out of interest, how would i extract the job name too? thank you so much :-)
Jamie
@Jamie, see my update (below the horizontal rule) as well as Amarghosh's. P.S. you never answered my question.
salathe
using the regex /\(\"(.*?)\"\)/ would match the job name
Xetius
@salathe, my apologies - which is quicker, using sscanf or using a regex match? "Are there any special conditions about grabbing the number?" Nopes, the number will only go from 1-99999. The message will always be in the same format.EDIT: Although, the message could change if the executed command returns an exit status of -1, but the regex wouldn't match so that shouldn't be a problem.
Jamie
sscanf would probably be quicker, but if the speed difference is a concern you should have mentioned that earlier. The regex is simple (even for the ones offered which match the job name) so I wouldn't expect it to be "slow" at all.
salathe
It's not a concern, i was just curious. Thanks very much for the answer/comments.
Jamie