import Foundation
// WARNING: You included a flag that Swift doesn't support: u
// When this flag is set, it makes the pattern and subject strings to be treated as unicode.
// Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.
let pattern = ##"(?<![\p{L}0-9])([##][·・ー_0-90-9a-zA-Za-zA-Zぁ-んァ-ン一-龠]{1,24})(?![\p{L}0-9])"##
let regex = try! NSRegularExpression(pattern: pattern)
let testString = ##"""
Hashtag must be started with # character.
Hashtag will be detected by space character and other special characters (!,@,&,*,%,$).
Example 1: Hello#guys. This is a #test. -> Valid hashtag: #test.
Example 2: Hello#guys. This is a #test!#message. -> Valid hashtag: #test and #message
Example 3: Hello#guys. This is a #test #message. -> Valid hashtag: #test and #message
Example 4: Hello#guys. This is a #test#message. -> Valid hashtag: #test
Example 5: #asdasdasdasdasdasdasdasdasd -> Valid hashtag: none
Example 6: # -> Valid hashtag: none
#日本語#asd => Valid hashtag should be #日本語
#日本語日本語日本語日本語日本語日本語日本語日本語日本語 => Will not a valid hashtag
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression