I try to come up with regular expression patter that fulfills such requirements.
- it is US phone number format wit 3 groups
- I have input strings like this
(999) 98__-9999
here there is extra_
at the end of second section which I want to delete
(999) 9_8_-9999
here there is extra _
at the end of second section I want to delete
(999) 9_-9999
here if second group length is < 3 and ends with _ there should be added _
to pad second group to 9__
(3 characters)
(999) 98-9999
here if second group length is equal to 3 or it ends with digit there shouldn't be any modifications
To sum up:
If secondGroup.length > 3 && secondGroup.lastCharacter == '_'
I want to remove
this last character
else if secondGroup.length < 3 && secondGroup.lastCharacter == '_'
I wan to append "_"
(or pad wit underscore to have 3 characters in total)
else leave
second group as in the input string.
The same should be applied to first group. The difference are the different delimiters i.e. (xxx) in first group and \sxxx- in second group
Here is my Swift code I have used to achieve it in brute force way by manually manipulating the string: (length 4 instead of 3 takes into account first delimiter like (
or \s
. )
var componentText = ""
let idx1 = newText.index(of: "(")
let idx2 = newText.index(of: ")")
if let idx1 = idx1, let idx2 = idx2 {
var component0 = newText[..<idx1]
var component1 = newText[idx1..<idx2]
if component1.count > 4 && component1.last == "_" {
component1.popLast()
} else if component1.count < 4 && component1.last == "_" {
component1.append("_")
}
componentText += "\(component0)\(component1))"
} else {
componentText = newText
}
let idx3 = newText.index(of: " ")
let idx4 = newText.index(of: "-")
if let idx2 = idx2, let idx3 = idx3, let idx4 = idx4 {
var component2 = newText[idx2..<idx3]
component2.popFirst()
var component3 = newText[idx3..<idx4]
var component4 = newText[idx4...]
if component3.count > 4 && component3.last == "_" {
component3.popLast()
} else if component3.count < 4 && component3.last == "_" {
component3.append("_")
}
componentText += "\(component2) \(component3)-\(component4)"
} else {
componentText = newText
}
newText = componentText != "" ? componentText : newText
I think that using regular expression this code could be more flexible and much shorter.