【发布时间】:2018-06-13 05:40:35
【问题描述】:
我目前正在使用正则表达式来查找我的应用之前创建的一些文件,但是我遇到了德语“Umlauten”问题,例如 ö,ä,ü。如果字符串中有“元音变音”,我的表达式不匹配。我想这与语言环境有关,但我不知道要设置什么语言环境(已经尝试过 nil)。
这里有一些代码:
// Building the regex
var regex = somePrefix + "_("
for string in stringArray{
regex += string + "|" // string can contain öäü
}
regex.remove(at: regex.index(before: regex.endIndex))
regex += ")_w\\d_d\\d"
// Finding files
let fileManager = FileManager()
let files = fileManager.enumerator(atPath: somePath)
while let file = files?.nextObject() {
let fileName = file as! String
if fileName.range(of: regex, options: .regularExpression, range: nil, locale: Locale.current) != nil {
print(fileName + " found")
}
}
// 一些不匹配的例子:
Regex = reis 8_(Ibedir|Drölf )_w\d_d\d
Filename that didnt match = reis 8_Drölf _w0_d0.plist
【问题讨论】:
-
这可能会有所帮助,这些字符是 unicode:stackoverflow.com/questions/29756530/…
-
你能举一个文件名和模式与预期不匹配的具体例子吗?
-
@MartinR 我添加了一个例子
-
这可能是 Unicode 规范化问题。尝试将
.decomposedStringWithCanonicalMapping添加到文件名和/或模式中。 -
将它添加到两者中就可以了。将其发布为答案,我会接受。
标签: regex swift locale file-handling