问题
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