Home > Software design >  Regex - Extract the first word from a string
Regex - Extract the first word from a string

Time:12-23

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

CodePudding user response:

(?<=Recipient Name: )([^ ] ) .*(?= SKU)

This Works

CodePudding user response:

Use \S to match a sequence of non-whitespace characters, instead of .*, to get one word.

let text = 'Recipient Name: Tracy Chan SKU: 103990';
let match = text.match(/(?<=Recipient Name: )\S /);
console.log(match[0]);

CodePudding user response:

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"

  • Related