RegEx用于匹配句子中间的名字

时间:2019-05-05 18:15:34

标签: javascript regex string

我试图捕获段落中的名称,并将其作为数组返回。具有名称的句子包含“ names are”。示例:

  

第一句话。一些第二句话。第三句和名字   是约翰,简,仁。这是关于其他内容的第四句话。

所需的输出:

[“约翰”,“简”,“简”]

尝试

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

2 个答案:

答案 0 :(得分:1)

您可以使用names are ([^.]+)来匹配所有内容,直到下一个时期。然后使用split将名称获取到数组

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)

答案 1 :(得分:1)

您可以在匹配后使用split()

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)