我可以阻止我的捕获组被覆盖吗?
Can I stop my capture group from being overwritten?
我正在尝试捕获 phone 数字中使用的第一个分隔符,以便识别用作数字内部分隔符的内容以及用于分隔两个数字的内容。
现在我可以识别最后一个分隔符。每次拾取新值时,似乎都会覆盖捕获组。无论如何保留使用标志或特定 swift 方法首先捕获的内容?
(?:\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
}
}
您需要使用这个正则表达式:
\d+([-. ])[-.\d]*
获取分隔符,它将在捕获组中
我正在尝试捕获 phone 数字中使用的第一个分隔符,以便识别用作数字内部分隔符的内容以及用于分隔两个数字的内容。
现在我可以识别最后一个分隔符。每次拾取新值时,似乎都会覆盖捕获组。无论如何保留使用标志或特定 swift 方法首先捕获的内容?
(?:\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
}
}
您需要使用这个正则表达式:
\d+([-. ])[-.\d]*
获取分隔符,它将在捕获组中