Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/110.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 正则表达式不在swift中工作。“给出错误”;“无效正则表达式”;_Ios_Swift_Objective C_Regex_Swift5 - Fatal编程技术网

Ios 正则表达式不在swift中工作。“给出错误”;“无效正则表达式”;

Ios 正则表达式不在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 {

我正在尝试从一个字符串中获取子字符串。为此,我正在应用regex
{[^{]*}
,但它在我的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尝试使用
{[^}]*}
,但仍然得到相同的错误。转义它。例如,
“\{.*}”
“\{[^}]*}”