我试图捕获电话号码中使用的第一个分隔符,以便识别用作数字内部分隔符的内容以及用于分隔两个数字的内容。
现在我可以识别最后一个分隔符。每次拾取新值时,都会覆盖捕获组。无论如何保留使用旗帜或特定的快速方法首先捕获的东西?
(?:\\d([\\-\\. ])?){7,15}
Swift方法
func regexParse(pattern:String, captureGroup:Int, caseSensitive:Bool) ->[String]
{
do
{
//Creates empty results array.
var resultsArray = [String]()
//Sets Case sensitivity
var caseSensitivity = NSRegularExpressionOptions.CaseInsensitive
if(caseSensitive)
{
caseSensitivity = NSRegularExpressionOptions.init(rawValue: 0)
}
//Sets regex to correct pattern
let regex = try NSRegularExpression(pattern: pattern, options: caseSensitivity)
//Converts string to NSString as swift doesn't support regex
let nsString = self as NSString
//Sets parsing range to the entire string
let all = NSMakeRange(0, nsString.length)
//Enumerates through all matches and extracts the 1st capture bracket for each match and adds it to the resultsArray.
regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) { (result: NSTextCheckingResult?, _, _) in
let capturedRange = result!.rangeAtIndex(captureGroup)
if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0))
{
let theResult = nsString.substringWithRange(capturedRange)
resultsArray.append(theResult)
}
}
return resultsArray
}
catch
{
print("Invalid regex")
return(["Error"]) //Maybe refactor this for something that's impossible to be a valid result
}
}
答案 0 :(得分:1)
您需要使用此正则表达式:
\d+([-. ])[-.\d]*
获取将在捕获组中的分隔符