代码之家  ›  专栏  ›  技术社区  ›  Code Guy

Regex模拟js split函数并提取文本

  •  0
  • Code Guy  · 技术社区  · 3 年前

    我有一个文本,我需要提取社区名称 拆分的分隔符为“-”

    因此 Iowa - Cedar Rapids - Meth-Wick Community Meth-Wick Community

    如果输入是 Iowa - Cedar Rapids - The Gardens of Cedar Rapids 结果必须是 The Gardens of Cedar Rapids

    "Iowa - Cedar Rapids - The Gardens of Cedar Rapids".match(new RegExp(/([A-Z])\w{3}/gi))
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   codehead    3 年前

    试试这一款的尺码:

    console.log("Iowa - Cedar Rapids - The Gardens of Cedar Rapids".replace(/([\w\s]+)\s-\s([\w\s]+)\s-\s([\w\s]+)/i,'$3'));
        2
  •  1
  •   shri_world    3 年前

    https://stackoverflow.com/a/8374980/5417843 然后从中提取社区名称。

    input = "Iowa - Cedar Rapids - The Gardens of Cedar Rapids"
    communityName = input.match(new RegExp('- (?:.(?!- ))+$')) // '- The Gardens of Cedar Rapids'
    communityName[0].substring(2) // 'The Gardens of Cedar Rapids'