Ios 正则表达式不在swift中工作。“给出错误”;“无效正则表达式”;
我正在尝试从一个字符串中获取子字符串。为此,我正在应用regexIos 正则表达式不在swift中工作。“给出错误”;“无效正则表达式”;,ios,swift,objective-c,regex,swift5,Ios,Swift,Objective C,Regex,Swift5,我正在尝试从一个字符串中获取子字符串。为此,我正在应用regex{[^{]*},但它在我的swift代码中不起作用,并给我一个错误“invalid regex”。同一个regex正在使用。我正在使用以下代码来应用regex。我需要在“{”和“}”之间获取子字符串。不使用regex我能得到相同的结果吗?或者我的regex或代码有什么问题吗 static func matches(regex: String, text: String) -> Bool { do {
{[^{]*}
,但它在我的swift代码中不起作用,并给我一个错误“invalid regex”。同一个regex正在使用。我正在使用以下代码来应用regex。我需要在“{”和“}”之间获取子字符串。不使用regex我能得到相同的结果吗?或者我的regex或代码有什么问题吗
static func matches(regex: String, text: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
let nsString = text as NSString
let match = regex.firstMatch(in: text, options: [],
range: NSRange(location: .zero, length: nsString.length))
return match != nil
} catch {
print("invalid regex: \(error.localizedDescription)")
return false
}
}
大括号是必须转义的特殊字符
\{[^}]*\}
,以快速文字字符串\{[^}]*\}
顺便说一下,不要使用NSRange
的文本初始值设定项来获取字符串的长度,强烈建议使用
static func matches(regex: String, text: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex, options: .caseInsensitive)
let match = regex.firstMatch(in: text, options: [],
range: NSRange(text.startIndex..., in: text)
return match != nil
} catch {
print("invalid regex: \(error.localizedDescription)")
return false
}
}
首先,您需要这样的正则表达式
{[^}]*}
其次,尝试转义字符,例如{
和}
@MichałTurczyn尝试使用{[^}]*}
,但仍然得到相同的错误。转义它。例如,“\{.*}”
或“\{[^}]*}”
。