正则表达式中,用于查找某些内容之前或者之后的东西,叫做断言。

(?=exp)用于匹配的位置前面能匹配到的值 (?<=exp)用于匹配的位置后面能匹配到的值 (?!exp)用于匹配值后面不能是exp (?<!exp)用于匹配值前面不能是exp

举例1:

//oc提取出 `<` 和 `>` 中间的json字符串
NSString *searchText = @"警方调查后发现真的是逃犯\"\n<{\"link\":{\"to\":\"problem\",\"key_val\":\"501\",\"text\":\"详情\"}}>";
NSString *regex = @"(?<=<).*?(?=>)" ;
NSRange range = [searchText rangeOfString:regex options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
     NSLog(@"%@", [searchText substringWithRange:range]);
}

举例2:

//js提取 `答案1`和`答案2`
var testString2 = `***** 
我是一个问题
答案1
答案2
*****`;

var res = testString2.match(/(?<=\n我是一个问题)[\s\S]*?(?=\*{5})/g); //返回数组
console.log(res);

其他swift:

 func matches(for regex: String, in text: String) -> [String] {
        
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: text,
                                        range: NSRange(text.startIndex..., in: text))
            return results.map {
                String(text[Range($0.range, in: text)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }

或者直接:

string.range(of: "109", options: NSString.CompareOptions.init(rawValue: 1024))

1024表示的是NSRegularExpressionSearch的枚举

js举例

reg = /POLYGON\((.*?)\)/gi;

"POLYGON((118.257206432 35.142103492,118.261146368 35.1419743060001,118.261430013 35.1417178180001,118.260999498 35.137444895,118.260715327 35.1372872520001,118.256472888 35.1374869860001,118.257093814 35.1420241000001,118.257206432 35.142103492)),POLYGON((118.261576135 35.1385784340001,118.266236568 35.1384064650001,118.266269116 35.1384018200001,118.266129093 35.1371199160001,118.266007014 35.1370334690001,118.261688791 35.137240954,118.261460704 35.137432776,118.261576135 35.1385784340001))".match(reg) 


(2) ["POLYGON((118.257206432 35.142103492,118.261146368 …3814 35.1420241000001,118.257206432 35.142103492)", "POLYGON((118.261576135 35.1385784340001,118.266236…0704 35.137432776,118.261576135 35.1385784340001)"]