【问题标题】:Tokenize String for words including non-word characters为包含非单词字符的单词标记字符串
【发布时间】:2013-04-28 21:52:21
【问题描述】:

我想标记 Twitter 消息,包括哈希和现金标签。标记化的正确示例如下:

"Bought $AAPL today,because of the new #iphone".match(...);
>>>> ['Bought', '$AAPL', 'today', 'because', 'of', 'the', 'new', '#iphone']

我为此任务尝试了几个正则表达式,即:

"Bought $AAPL today,because of the new #iphone".match(/\b([\w]+?)\b/g);
>>>> ['Bought', 'AAPL', 'today', 'because', 'of', 'the', 'new', 'iphone']

"Bought $AAPL today,because of the new #iphone".match(/\b([\$#\w]+?)\b/g);
>>>> ['Bought', 'AAPL', 'today', 'because', 'of', 'the', 'new', 'iphone']

"Bought $AAPL today,because of the new #iphone".match(/[\b^#\$]([\w]+?)\b/g);
>>>> ['$AAPL', '#iphone']

我可以使用哪个正则表达式来在标记中包含前导的尖号或美元符号?

【问题讨论】:

  • @Ejay:有时人们也会使用.!?
  • 抱歉在阅读你之前删除了我的评论 :) "Bought $AAPL today,because of the new #iphone".match(/[^ ,\!\?\.]+/g)
  • 实际上可以请您发布可能字符串的示例吗?编辑:你有答案:)

标签: javascript regex tokenize


【解决方案1】:

明显的怎么样

"Bought $AAPL today,because of the new #iphone".match(/[$#]*\w+/g)
// ["Bought", "$AAPL", "today", "because", "of", "the", "new", "#iphone"]

?

PS:[$#]* 可能会替换为[$#]?,不确定具体要求。

【讨论】:

  • 这行得通,我认为使用单词分隔符 (\b) 会更省钱,但我现在想不出适用的边缘情况,所以你的解决方案应该可以工作非常完美,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
相关资源
最近更新 更多