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}+\P{L}+){1,3})(p[oó][zž][ií][cč][ií])($|(?:\P{L}+\p{L}+){1,3})"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = ##"""
Ahoj,
potřebuji najít pozici slova v textu (a pak ukázat kousek textu před a po, resp víc slov hledám, ale pro demonstraci, stačí 1 slovo).
Mám tedy nějaká text, zkusím vyhledat třeba slovo „Richter“ (potřebuji aby to umělo s diakritikou i bez), takže jsem použil regexp a zjištuju kde je zase problém.
funkce strpos samozřejmě nefunguje dobře (díky multi-byte kódování ukáže jinou pozici než by měla)
funkce mb_strpos se zachová správně (kdo by to byl čekal ;-))
preg_match_all se chová stejně „hloupě“ jako strpos
našel jsem v komentářích starou funkci upravenou o „MB“ chování a ta funguje dobře (jako mb_strpos) více na php.net (https://www.php.net/…atch-all.php#…)
vyzkoušel jsem si matchAll z balíčku Strings a funguje stejně špatně jako preg_match_All
"""##
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