我正在使用此代码从我的 Rails 3.2.13 应用程序中的帖子中提取主题标签。我也在使用 Ruby 1.9.3。
hasy =/(?:\s|^)(?:#(?!(?:\d+|\w+?_|_\w+?)(?:\s|$)))(\w+)(?=\s|$)/i
tags =post.body.scan(hasy).join(',').split(',').map{|i| "#"+i}
该代码对于英语单词非常有效,但对于其他语言,特别是阿拉伯语,它们不起作用。 有没有人有解决问题的想法,因为我的网站使用了很多阿拉伯语文本。
最佳答案
我建议查看 POSIX 字符类的 Regexp 文档。有几个可能适合您的需要。我建议以 [:graph:]
作为起点,然后根据需要缩小范围。
来自 the docs :
/[[:alnum:]]/ - Alphabetic and numeric character
/[[:alpha:]]/ - Alphabetic character
/[[:blank:]]/ - Space or tab
/[[:cntrl:]]/ - Control character
/[[:digit:]]/ - Digit
/[[:graph:]]/ - Non-blank character (excludes spaces, control characters, and similar)
/[[:lower:]]/ - Lowercase alphabetical character
/[[:print:]]/ - Like [:graph:], but includes the space character
/[[:punct:]]/ - Punctuation character
/[[:space:]]/ - Whitespace character ([:blank:], newline, carriage return, etc.)
/[[:upper:]]/ - Uppercase alphabetical
/[[:xdigit:]]/ - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)
Ruby also supports the following non-POSIX character classes:
/[[:word:]]/ - A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation
为了您的目的,像这样:
/\s(#[[:graph:]]+)/
will capture your two sample strings .之前的 Rubular 链接有示例。
关于ruby - 如何从非英语字符串中提取主题标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875013/