我正在使用此代码从我的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}
该代码适用于英语单词,但对于其他语言,特别是阿拉伯语,它们不起作用。 有没有人有解决问题的想法,因为我的网站使用了大量的阿拉伯文字。
答案 0 :(得分:3)
\w
只会匹配ASCII字符。您可以在正则表达式中使用POSIX bracket expressions来匹配Unicode中被视为字母字符的非ASCII字符。
str = "some text before #القاهرة more text here القاهرة #foobar"
str.scan(/#[[:alnum:]]+/)
# => ["#القاهرة", "#foobar"]
答案 1 :(得分:2)
我建议查看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还支持以下非POSIX字符类:
/[[: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链接有例子。
答案 2 :(得分:0)
[^\x20-\x7E]+
将识别非ASCII字符。