Regular Expression for reverse name

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

Moderator: General Moderators

Post Reply
anshuk
Forum Newbie
Posts: 2
Joined: Sat Mar 17, 2012 11:38 am

Regular Expression for reverse name

Post 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??
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Regular Expression for reverse name

Post 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})*?)
anshuk
Forum Newbie
Posts: 2
Joined: Sat Mar 17, 2012 11:38 am

Re: Regular Expression for reverse name

Post by anshuk »

strangely nope that doesnt work!!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Regular Expression for reverse name

Post 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?
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: Regular Expression for reverse name

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