How can I use the replacingOccurrences with regex and only replace the first occurrence?
Example
var str = "= 1 = 2 = 3"
str = str.replacingOccurrences(of: "(\\d+)", with: "\\\\$1", options: .regularExpression)
// prints: = \\1 = \\2 = \\3
// should print: = \\1 = 2 = 3
The dropFirst() method removes the first character of the string.
In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.
String.range()
will stop at the first match:
var str = "= 1 = 2 = 3"
if let range = str.range(of: "\\d+", options: .regularExpression) {
let substr = str[range]
str = str.replacingCharacters(in: range, with: "\\\\" + substr)
}
print(str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With