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

后端 未结 3 1430
清歌不尽
清歌不尽 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

    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/

提交回复
热议问题