Sepero
Sepero

Reputation: 4677

RegEx for matching first names in the middle of sentences

I'm trying to capture names in a paragraph, and return them as an array. The sentence with the names contains "names are". Example:

The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.

Desired Output:

[ "John", "Jane", "Jen" ]

Attempt

paragraph.match(/names are ([A-Za-z ]+,{0,1} {0,1})+\./)

Upvotes: 1

Views: 166

Answers (2)

adiga
adiga

Reputation: 35222

You could use names are ([^.]+) to match everything until the next period. Then use split to get the names to an array

const str = 'The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.'

const regex = /names are ([^.]+)/,
      names = str.match(regex)[1],
      array = names.split(/,\s*/)

console.log(array)

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

You can use split() after matching

let str = `The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.`

let res = str.match(/names are ([A-Za-z ]+,{0,1} {0,1})+\./g)[0].split(/\s+/g).slice(2)
console.log(res)

Upvotes: 1

Related Questions