Regex for a (twitter-like) hashtag that allows non-ASCII characters

天涯浪子 提交于 2019-11-27 15:06:53
limlim

Eventually I found this: twitter-text.js useful link, which is basically how twitter solve this problem.

With native JS regexes that don't support unicode, your only option is to explicitly enumerate characters that can end the tag and match everything else, for example:

> s = "foo #הַתִּקְוָה. bar"
"foo #הַתִּקְוָה. bar"
> s.match(/#(.+?)(?=[\s.,:,]|$)/)
["#הַתִּקְוָה", "הַתִּקְוָה"]

The [\s.,:,] should include spaces, punctuation and whatever else can be considered a terminating symbol.

#([^#]+)[\s,;]*

Explanation: This regular expression will search for a # followed by one or more non-# characters, followed by 0 or more spaces, commas or semicolons.

var input = "#hasta #mañana #babהַ";
var matches = input.match(/#([^#]+)[\s,;]*/g);

Result:

["#hasta ", "#mañana ", "#babהַ"]

EDIT - Replaced \b for word boundary

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