本文介绍了Swift Xcode6 beta6 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式获取字符

I want to get the characters using regex

我想获得CDE"

var results : NSMutableArray;
var baseString = "ABCDEFG"
var regexp  = NSRegularExpression(pattern: "AB.*?FG", options: nil, error: nil)
var match : NSArray = regexp.matchesInString(baseString, options: nil, range: NSMakeRange(0,countElements(baseString)));

for matches in match {
    results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
}
println(results);//print"CDE"

但我得到错误.错误→

results.addObject(sampleString.substringWithRange(matches.rangeAtIndex(2)));
NSRange' is not convertible to 'Range<String.Index>'

我的英语不好.对不起..请帮帮我...

my english isn't good.sorry..please help me...

推荐答案

正则表达式不正确,匹配将是整个字符串.而是使用:(?<=AB).*?(?=FG).

The regular expression is incorrect, the match will be the entire string. Instead use: (?<=AB).*?(?=FG).

文档:ICU 用户指南 正则表达式

Documantation: ICU User Guide Regular Expressions

注意事项:

(?<=AB) means preceded by AB
(?=FG)  means followed by FG

这些不捕获匹配的部分.

These do not capture the matched portion.

示例代码:

var baseString = "ABCDEFG"
var pattern = "(?<=AB).*?(?=FG)"
if let range = baseString.rangeOfString(pattern, options: .RegularExpressionSearch) {
    let found = baseString.substringWithRange(range)
    println("found: \(found)")
}

输出:

找到:CDE

这篇关于Swift Xcode6 beta6 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:08