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

从文本中获取所有单词,包括附加到这些单词的任何特殊字符

  •  1
  • Cybernetic  · 技术社区  · 6 年前

    我有这样的文字:

    Here is some text.
    
    #note Remember to look into specs #
    
    And here is some more text.
    

    我可以使用以下方法获取该文本中的所有单词(str是所有文本):

    str.match(/\w+/g)
    

    这提供了一个包含所有单词的数组,但hashtag已从该单词中删除。 笔记 :

    Here,is,some,text,note,Remember,to,look,into,specs,And,here,is,some,more,text
    

    我怎样才能得到这样的结果呢 包括hashtag 关于它所附的词?

    预期结果: Here,is,some,text,#note,Remember,to,look,into,specs,And,here,is,some,more,text

    4 回复  |  直到 6 年前
        1
  •  2
  •   Dacre Denny    6 年前

    你可以通过增加 .? 到正则表达式。

    这个 ? 是一个特殊字符,意思是“零或之一”,并且 . 表示任何字符(特殊或非特殊)。

    结合 ? 因此,松散地表示“在单词开头匹配可选的特殊字符”:

    str.match(/.?\w+/g)
    

    这里的假设是,您只想匹配单词开头的特殊字符(即 可选前缀 有一些特殊的特征)。你可以阅读更多关于 ? 在正则表达式中 at the MDN documentation

        2
  •  2
  •   Ele    6 年前

    另一种选择是使用这个regex (.+?\w+) 它可以在一个单词前或只在一个单词前找到任意数量的字符。这种方法也得到了空间,因此函数 map 删除这些空格。

    一些解释: https://regex101.com/r/fEBDeY/1

    console.log(`Here is some text.
    
    #note Remember to look into ****specs #
    
    And here is some more text.`.match(/(.+?\w+)/g).map(s => s.trim()));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    另一种方法是使用函数 split 它接收一个regex,这个方法使用这个 \s+ .

    console.log(`Here is some text.
    
    #note Remember to look into ****specs #
    
    And here is some more text.`.split(/\s+/g));
    .作为控制台包装最大高度:100%!重要;顶部:0;
        3
  •  0
  •   Karan Dhir    6 年前

    那是因为 \w 元字符用于查找单词字符。 如果要包含每个字符,可以使用 . 元字符,用于查找单个字符(换行符或其他行终止符除外):

    str.match(/./g)

        4
  •  0
  •   Jeet Parekh    6 年前

    你可以只匹配非空白字符- /(\S\w+)/gm .

    在这里,它在行动- https://regex101.com/r/Oj2Vhw/2/