0

我正在尝试解析一些推文,但在使用正则表达式删除以@符号和#符号开头的单词时遇到问题。我努力了

tweet.slice!("#(\S+)\s?")
tweet.slice!("@(\S+)\s?")

tweet.slice!("/(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/i")
tweet.slice!("/(?:\s|^)(?:@(?!\d+(?:\s|$)))(\w+)(?=\s|$)/i")

tweet.slice!("\#/\w/*")
tweet.slice!("\@/\w/*")

而且它们似乎都不起作用。我只是做错了什么吗?

4

2 回答 2

0

您可以使用gsub!和单词边界来做到这一点。

tweet.gsub!(/\B[@#]\S+\b/, '')

正则表达式:

\B         the boundary between two word chars (\w) or two non-word chars (\W)
[@#]       any character of: '@', '#'
\S+        non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)       
\b         the boundary between a word char (\w) and something that is not a word char
于 2013-10-06T04:41:28.953 回答
0

使用String#gsub!

>> tweet = 'Hello @ruby #world'
=> "Hello @ruby #world"
>> tweet.gsub!(/[#@]\w+/, '')
=> "Hello  "
>> tweet
=> "Hello  "
于 2013-10-06T04:24:31.923 回答