如何在使用 lodash _.words 时不在 dash/hyphen 上分离?

How to not separate on dash/hyphen when using lodash _.words?

我正在使用 lodash 将提供给我的用户名拆分为带有某种任意分隔符的字符串。我想使用 _.words() 将字符串拆分成单词,连字符除外,因为一些用户名包含连字符。

示例:

_.words(['user1,user2,user3-adm'], RegExp)

我希望它产生:

['user1', 'user2', 'user3-adm']

不是这个(_.words(数组)没有任何模式):

['user1', 'user2', 'user3', 'adm']

什么是正确的 String/RegExp 来实现这一目标?

words 接受正则表达式来匹配单词并且 不拆分 它们,既然如此,只需使用匹配除逗号之外的所有内容的正则表达式,即:

_.words(['user1,user2,user3-adm'], /[^,]+/g);

或者,您可以使用 split

result = wordlist.split(/,/);

https://lodash.com/docs#words

最初的情况可以这样解决:

_.words(['user1,user2,user3-adm'], /[^,]+/g);

结果:

["user1", "user2", "user3-adm"]

[已编辑]

如果要添加更多分隔符,请这样添加:

_.words(['user1,user2,user3-adm.user4;user5 user7'], /[^,.\s;]+/g);

结果:

["user1", "user2", "user3-adm", "user4", "user5", "user7"]

最后一个片段将分隔:

逗号 (,), 点(.), 空格 (\s), 分号 (;)


或者您可以使用:

 _.words(['user1,user2,user3-adm.user4;user5 user7*user8'], /[-\w]+/g)

结果:

 ["user1", "user2", "user3-adm", "user4", "user5", "user7", "user8"]

在这种情况下,您可以添加您不需要的内容作为分隔符。在这里它将被每个不是 \w(与 [_a-zA-Z0-9] 相同)或 -(破折号)

的字符分隔