Page 1 of 1

Regular Expression for reverse name

Posted: Sat Mar 17, 2012 11:59 am
by anshuk
Hi,

I have been stuck at this problem for sometime now; I have to capture the last first name and title from the following sample string

1.LASTNAME/FIRSTNAME MIDDLENAME1 MIDDLENAME2 MIDDLENAME3 .. MIDDLENAMEn TITLE

FIRSTNAME and MIDDLENAME may not be present
now TITLE can be one of these values MR / MISS / MRS / MSTR / MASTER only; or it could be blank like FIRSTNAME and MIDDLENAME

(?<number>\d+)\.(?<surname>[a-z\s]*)\/((?<firstname>[a-z]+\s{0,1}))*(?<title>mrs|mr|miss|mstr|master){0,1}

In PHP preg_match does not do the trick as the firstname group doesnt capture mutiple values

how can i do this??

Re: Regular Expression for reverse name

Posted: Sat Mar 17, 2012 7:29 pm
by requinix
Move the naming outside and move the star (with a question mark to make it lazy so it doesn't accidentally pick up the title) inside.

Code: Select all

(?<firstname>([a-z]+\s{0,1})*?)

Re: Regular Expression for reverse name

Posted: Sun Mar 18, 2012 1:08 am
by anshuk
strangely nope that doesnt work!!

Re: Regular Expression for reverse name

Posted: Sun Mar 18, 2012 1:59 am
by requinix
The only difference between what you posted (after the change) and the working version I have is the end-of-string anchor at the end. Does your actual code have that?

Re: Regular Expression for reverse name

Posted: Mon Mar 19, 2012 8:36 pm
by ragax
Wow, my post from yesterday disappeared. I was having connection problems. Probably it never made it through?
Luckily, I still have the code. :)

Anshuk, try this. Group 1 captures the last name, Group 2 captures the first name, Group 3 captures the title.

Input:
1.LASTNAME/firstname MIDDLENAME1 MIDDLENAME2 MIDDLENAME3 MIDDLENAME miss

Code:

Code: Select all

<?php
$regex=',^\d+\.(\w+)(?:/(\w+))?\s(?:\w+(?:\s))*(?:(m(?:rs|r|iss|str|aster))|\w+)$,i';
$string='1.LASTNAME/firstname MIDDLENAME1 MIDDLENAME2 MIDDLENAME3 MIDDLENAME miss';
preg_match($regex,$string,$m);
echo 'Last: '.$m[1].'<b@r />';
echo 'First: '.$m[2].'<b@r />';
echo 'Title: '.$m[3].'<b@r />';
?>
Remove the @ in the three b@r, I put it there because otherwise the forum displays line breaks!

Output:
Last: LASTNAME
First: firstname
Title: miss

Let us know if this helps and you have any more questions. :)