Home > OS >  Explain strange sign " ^ " in phone number format
Explain strange sign " ^ " in phone number format

Time:06-27

I found the solution to format phone numbers in textfield. Could you explain me what this sign ^ stands for in this line let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return false }
    let newString = (text as NSString).replacingCharacters(in: range, with: string)
    textField.text = format(with: " X (XXX) XXX-XXXX", phone: newString)
    return false
}

func format(with mask: String, phone: String) -> String {
    let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
    var result = ""
    var index = numbers.startIndex
    for ch in mask where index < numbers.endIndex {
        if ch == "X" {
            result.append(numbers[index])
            index = numbers.index(after: index)
        } else {
            result.append(ch)
        }
    }
    return result
}

CodePudding user response:

The symbol ^ is caret . It has two meaning in regular expression.

The ^a matches only a if it is at the beginning of string(Demo Link). Here ^ is playing role of anchor .It is positioned before the start of the string and then character is matched. It simply instruct the regex engine to match from the beginning of the string. There are other anchors as well in the regular expression.

Now coming to you regex .The [^0-9] expression is used to match any character that is NOT a digit.[] is a character class. Through this we can tell the regex engine to match only one out of several characters mentioned within character class. [^] is negated character class matches only a character which is not inside the negated character class. Here ^ is playing role for negation .

I would suggest you to read about regular expression to grasp the answer completely.

  • Related