Lee
Lee

Reputation: 3012

JavaScript RegEx partial match/return only matched value of one group

Let me use one example to explain my question. Let's say we have a RegEx to match a person's title and name, we define RegEx as

/(Mr|Mdm|Madam|Ms|Miss|Dr\.?)\s+([A-Z][a-z]+\s){1,4}/gm;

And if we match this against a long text

I spoke to Mr John Smith and he would like to refer me to Dr Baska

the RegEx will return me two matched entries

My question is how to make the string.match (RegEx) return me only an array of names without title?

UPDATE

I saw documentation about group operator () in MDN mentioning remembering group with \1, \2 etc, but not sure syntactically if this can be used for the purpose mentioned above.

Upvotes: 1

Views: 608

Answers (2)

ndnenkov
ndnenkov

Reputation: 36110

Javascript regexes don't support lookbehinds. Therefore, you either have to extract the groups or do some processing afterwards:

var sentence = 'I spoke to Mr John Smith and he would like to refer me to Dr Baska';
var nameFinder = /(Mr|Mdm|Madam|Ms|Miss|Dr\.?)\s+([A-Z][a-z]+\s?){1,4}/gm;

sentence.match(nameFinder).map(function(name) {
    return name.replace(/^\S+\s/, '').trim();
}); // => ["John Smith", "Baska"]

Upvotes: 1

Tushar
Tushar

Reputation: 87223

You can use RegExp.exec with while loop to get the names of persons. To get the name, you can use the capturing groups.

var regex = /(Mr|Mdm|Madam|Ms|Miss|Dr)\.?\s+(([A-Z][a-z]+\s?){1,4})/g;
var str = "I spoke to Mr John Smith and he would like to refer me to Dr Baska";

// Declare array to store results
var persons = [];

while(match = regex.exec(str)) {
  // Trim the person name and add in the array
  persons.push(match[2].trim());
}

console.log(persons);
document.body.innerHTML = '<pre>' + JSON.stringify(persons, 0, 2) + '</pre>';

I've also made some changes in the RegEx to match and capture names of persons.

RegEx101 Demo

/(Mr|Mdm|Madam|Ms|Miss|Dr)\.?\s+((?:[A-Z][a-z]+\s?){1,4})/
                          ^^^                             : Made it common for all and optional
                                ^                       ^ : To capture complete name
                                 ^^^             ^^       : Made the non-capturing group and last space optional

Following regex can also be used with first captured group.

RegEx101 Demo

(?:Mr|Mdm|Madam|Ms|Miss|Dr)\.?\s+((?:[A-Z][a-z]+\s?){1,4})

Upvotes: 2

Related Questions