使用正则表达式匹配表情符号以及字符串中的文本 [英] Use regex to match emojis as well as text in string
问题描述
我试图找到一个字符串的特定子串的范围。每个子字符串都以一个hashtag开头,并且可以包含它喜欢的任何字符(包括emojis)。应在不同范围检测重复的主题标签。一位来自此处的用户建议使用以下代码:
I am trying to find the range of specific substrings of a string. Each substring begins with a hashtag and can have any character it likes within it (including emojis). Duplicate hashtags should be detected at distinct ranges. A kind user from here suggested this code:
var str = "The range of #hashtag should be different to this #hashtag"
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: [])
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count))
for match in matches {
print("match = \(match.range)")
}
但是,此代码不适用于emojis。包含表情符号的正则表达式是什么?有没有办法检测#
,然后是空格/换行符之前的任何字符?
However, this code does not work for emojis. What would be the regex expression to include emojis? Is there a way to detect a #
, followed by any character up until a space/line break?
推荐答案
类似地如夫特提取的正则表达式匹配 ,
你必须将 NSRange
传递给匹配函数,而
返回的范围是 NSRange
s。这可以通过将给定文本转换为 NSString
来实现
。
Similarly as in Swift extract regex matches,
you have to pass an NSRange
to the match functions, and the
returned ranges are NSRange
s as well. This can be achieved
by converting the given text to an NSString
.
#\ S +
模式匹配#
后跟一个或多个
非空白字符。
The #\S+
pattern matches a #
followed by one or more
non-whitespace characters.
这篇关于使用正则表达式匹配表情符号以及字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!