0
我試圖捕獲電話號碼內使用的第一個分隔符,以便確定用作數字內部分隔符的內容以及用於分隔兩個數字的內容。我可以阻止我的捕獲組被覆蓋嗎?
現在我可以識別最後的分隔符。每次拾取新值時,捕獲組似乎都會被覆蓋。無論如何保留使用國旗或特定快速方法首先捕獲的內容?
(?:\\d([\\-\\. ])?){7,15}
斯威夫特方法
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
}
}
[像這樣](https://regex101.com/r/rF5qJ7/4)? –
@ThomasAyoub完美的感謝,隨時把它作爲答案。 – Deco