Reputation: 4677
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.
[ "John", "Jane", "Jen" ]
paragraph.match(/names are ([A-Za-z ]+,{0,1} {0,1})+\./)
Upvotes: 1
Views: 166
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
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