ruby - 如何从非英语字符串中提取主题标签?

标签 ruby regex

我正在使用此代码从我的 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/

相关文章:

ruby - 如何在 Sinatra 中使用 Pry?

ruby-on-rails - 如何在 Rails 4.2 中添加 JSON 文件导出功能

python - [^.]* 在正则表达式中是什么意思?

php - 使用 preg_replace 来字符日语

Python 正则表达式 行内的任一/或

ruby - 动态模块 : Querying tables with secondary index

ruby-on-rails - 如何从 ActiveRecord 中名为 "object_id"的列中检索值?

javascript - 给定以下 JS/JQUERY,如何防止它区分大小写

c# - 从 REGEX 生成测试数据

ruby - 在 Ruby 中检索字符串的最后一部分?