提问者:小点点

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


我正在尝试在段落中捕获名称,并将它们作为数组返回。具有名称的句子包含“name are”。例子:

第一句。第二句。第三句,名字是约翰、简、珍。这是关于其他东西的第四句。

[“约翰”“简”“只是”]

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

共2个答案

匿名用户

您可以使用名称 ([^.] )来匹配直到下一个周期的所有内容。然后使用拆分将名称获取到数组

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)

匿名用户

匹配后可以使用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)