2

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

  • Last name start with letter "S"
  • First name NOT start with letter "S"

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:

  • (Last name) (First name)
  • Duncan, Jean
  • Schmidt, Paul
  • Sells, Simon
  • Martin, Jane
  • Smith, Peter
  • Stephens, Sheila

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

Community
  • 1
  • 1
BbGreaT
  • 31
  • 5

4 Answers4

1

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

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
1

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;
 }
Rui Fernandes
  • 270
  • 1
  • 11
0

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
Rinsad Ahmed
  • 1,877
  • 1
  • 10
  • 28
0

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])

The fourth bird
  • 154,723
  • 16
  • 55
  • 70