BbGreaT
BbGreaT

Reputation: 31

How to Extract people's last name start with "S" and first name not start with "S"

As the title shows, how do I capture a person who:

The expression should match the entire last name, not just the first letter, and first name should NOT be matched.

Input string is like the following:

This is my regular expression:

/([S].+)(?:, [^S])/

Here is the result I have got:

Schmidt, P Smith, P

the result included "," space & letter "P" which should be excluded.

The ideal match would be

Schmidt

Smith

Upvotes: 2

Views: 708

Answers (4)

Michał Turczyn
Michał Turczyn

Reputation: 37430

You can try this pattern: ^S\w+(?=, [A-RT-Z]).

^S\w+ matches any word (name in your case) that start with S at the beginning,

(?=, [A-RT-Z]) - positive lookahead - makes sure that what follows, is not the word (first name in your case) starting with S ([A-RT-Z] includes all caps except S).

Demo

Upvotes: 1

Rinsad Ahmed
Rinsad Ahmed

Reputation: 1933

Your regex worked for me fine

$array = ["Duncan, Jean","Schmidt, Paul","Sells, Simon","Martin, Jane","Smith, Peter","Stephens, Sheila"];
foreach($array as $el){
    if(preg_match('/([S].+)(?:,)( [^S].+)/',$el,$matches))
       echo $matches[2]."<br/>";
}

The Answer I got is

Paul
Peter

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163457

In you current regex you capture the lastname in a capturing group and match the rest in a non capturing group.

If you change your non capturing group (?: into a positive lookahead (?= you would only capture the lastname.

([S].+)(?=, [^S]) or a bit shorter S.+(?=, [^S])

Upvotes: 0

Rui Fernandes
Rui Fernandes

Reputation: 270

I did something similar to catch the initials. I've just updated the code to fit your need. Check it:

public static void Main(string[] args)
{
   //Your code goes here
   Console.WriteLine(ValidateName("FirstName LastName", 'L'));
}

private static string ValidateName(string name, char letter)
{
   // Split name by space

   string[] names = name.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);

   if (names.Count() > 0)
   {
      var firstInitial = names.First().ToUpper().First();
      var lastInitial = names.Last().ToUpper().First();

      if(!firstInitial.Equals(letter) && lastInitial.Equals(letter))
      {
         return names.Last();
      }
   }

   return string.Empty;
 }

Upvotes: 1

Related Questions