Extract hashtags from complex string using regex

不想你离开。 提交于 2019-11-30 09:36:13

问题


I have a crazy string, something like:

sun #plants #!wood% ##arebaba#tey   travel#blessed    #weed das#$#F!@D!AAAA

I want to extract all "words" (also containing special characters) that begin with # or that have a space right before, taking the following as a result:

[
  'sun',
  'plants',
  '!wood%',
  'arebaba',
  'tey',
  'travel',
  'blessed',
  'weed',
  'das',
  '$',
  'F!@D!AAAA'
]

How do I get this using regex?


回答1:


You can use match using regex: [^#\s]+:

var str = 'sun #plants #!wood% ##arebaba#tey   travel#blessed    #weed das#$#F!@D!AAAA';
    
var arr = str.match(/[^\s#]+/g);

console.log(arr);

RegEx Demo




回答2:


Just using match you could get all the group 1 matches into an array.

(?:^|[ #]+)([^ #]+)(?=[ #]|$)

Easy!

 (?: ^ | [ #]+ )
 ( [^ #]+ )                    # (1)
 (?= [ #] | $ )

Or, if you feel it's this simple, then just use ([^ #]+) or [^ #]+
which gets the same thing (like split in reverse).



来源:https://stackoverflow.com/questions/43398984/extract-hashtags-from-complex-string-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!