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

前端 未结 3 1310
遥遥无期
遥遥无期 2020-12-03 18:08

I want a regex to match a simple hashtag like that in twitter (e.g. #someword). I want it also to recognize non standard characters (like those in Spanish, Hebrew or Chinese

3条回答
  •  死守一世寂寞
    2020-12-03 18:29

    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.

提交回复
热议问题