代码之家  ›  专栏  ›  技术社区  ›  Hamid

使用javascript regex在大文本中查找首字母缩略词

  •  0
  • Hamid  · 技术社区  · 6 年前

    我有一篇大文章,里面有一些缩略词。所有的缩略词都在括号内,都是大写字母。在圆括号之前,总是有与括号中以相同字母开头的字母数量相同的单词。然而,这些单词可能不是以大写字母开头的。

    前任:

    雷达散射截面(RCS)雷达散射截面。。。

    3 回复  |  直到 6 年前
        1
  •  2
  •   Scott Sauyet    6 年前

    const findAcronyms = (str) => {
      const words = str.split(/\s+/)
      
      return words.reduce((all, word, i) => {
        const isCandidate = word.match(/\([A-Z]+\)/)
        if (!isCandidate) {return all}
        const letters = word.split('').slice(1, -1)
        const acro = letters.join('')   
        if (i - letters.length < 0) {return all}
        if (words.slice(i - letters.length, i)
            .map(s => s[0]).join('')
            .toLowerCase() !== acro.toLowerCase()) {
          return all
        }
        
        return {
          ...all, 
          [acro]: words.slice(i - letters.length, i).join(' ')
        }
      }, {})
    }
    
    const str = 'bla bla radar cross section (RCS) but this one (IN) is not And This One (ATO) is'
    
    console.log(findAcronyms(str)) //~>
    // {
    //   RCS: "radar cross section",
    //   ATO: "And This One"
    // }

    请注意 "IN" 不包含在结果中,因为它与前面的文本不匹配。

    如果您只需要实际的首字母缩略词,而不需要它们代表什么,那么可以将返回值修改为数组,或者只需运行 Object.keys

        2
  •  1
  •   Aziz.G    6 年前

    const str = "bla bla radar cross section (RCS) bla bla...(aaaaaa) stack overflow (SO)",
      acronymes = [],
      result = str.match(/\(([A-Z].*?)\)/g).map(val => {
        acronymes.push(val.substr(1, val.length - 2));
      });
    
    console.log(acronymes)
        3
  •  -1
  •   Gauri Dasgupta    6 年前

    你可以这样做:

    [\([A-Z]+[\)]