Skip to content
Advertisement

Regex – Extract the first word from a string

I want to parse the text below:

Recipient Name: Tracy Chan SKU: 103990

I want to extract “Tracy” only, the first word after “Recipient Name:” as the first name

So I got as far as /(?<=Recipient Name: )(.*)(?= SKU)/gm but it only gives me “Tracy Chan”…. Using the ECMA option in Regex101…

Appreciate any help on this.

Thanks, Tracy

Advertisement

Answer

To extract “Tracy” only, you can use the following regular expression:

/(?<=Recipient Name: )(S+)/gm

This will match the first word (i.e., the first sequence of non-whitespace characters) after the “Recipient Name:” string.

The S character class matches any non-whitespace character, and the + quantifier specifies that the preceding pattern should be matched one or more times until the first whitespace.

a working example:

const input = "Recipient Name: Tracy Chan SKU: 103990";
const regex = /(?<=Recipient Name: )(S+)/gm;
const matches = regex.exec(input);
console.log(matches[0]);  // "Tracy"

Update: based on your comments below, you also need to extract the last name from your string value. I would suggest to either use the original regex written in your question, or use this one, in order to extract both Tracy and Chan, then you can use the javascript split method` to split the string into an array with all the extracted names.

consider the following example:

const input = "Recipient Name: Tracy Chan SKU: 103990";
    const regex = /(?<=Recipient Name: )([^ ]+)s([^ ]+)/gm;
    const allMatches = input.match(regex);
    let resultArray = allMatches[0].split(' ');
    console.log('firstName: '+ resultArray[0]);  // "Tracy"
    console.log('lastName: '+ resultArray[1]);  // "Chan"
Advertisement