Javascript Regex match any word that starts with '#' in a string

后端 未结 3 1412
清歌不尽
清歌不尽 2020-12-16 02:58

I\'m very new at regex. I\'m trying to match any word that starts with \'#\' in a string that contains no newlines (content was already split at newlines).

Example (

相关标签:
3条回答
  • 2020-12-16 03:21
    var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
    while (match = re.exec(s)) {
      matches.push(match[1]);
    }
    

    Check this demo.

    0 讨论(0)
  • 2020-12-16 03:21

    You actually need to match the hash too. Right now you're looking for word characters that follow a position that is immediately followed by one of several characters that aren't word characters. This fails, for obvious reasons. Try this instead:

    string.match(/(?=[\s*#])[\s*#]\w+/g)
    

    Of course, the lookahead is redundant now, so you might as well remove it:

    string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);})
    

    This returns the desired: [ 'iPhone', 'delete' ]

    Here is a demonstration: http://jsfiddle.net/w3cCU/1/

    0 讨论(0)
  • 2020-12-16 03:39

    Try this:

    var matches = string.match(/#\w+/g);
    
    0 讨论(0)
提交回复
热议问题