【问题标题】:RegEx for matching first names in the middle of sentencesRegEx 用于匹配句子中间的名字
【发布时间】:2019-09-23 11:39:56
【问题描述】:

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

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

期望的输出:

[“约翰”、“简”、“珍”]

尝试

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

【问题讨论】:

标签: javascript regex string


【解决方案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)

【讨论】:

  • 你也可以只使用否定字符类而不是惰性匹配:([^.]+)\.
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多