Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the first occurence in Swift?

Tags:

regex

swift

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
like image 891
codeaddslife Avatar asked Jun 12 '17 04:06

codeaddslife


People also ask

How do I remove the first character from a string in Swift?

The dropFirst() method removes the first character of the string.

How do I remove a specific character from a string in Swift?

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.


1 Answers

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)
like image 124
Code Different Avatar answered Oct 24 '22 07:10

Code Different