Regular expression with backslash in swift

Viewed 288

i am having problems using replacingOccurrences to replace a word after some specific keywords inside a textview in swift 5 and Xcode 12.

For example: My textview will have the following string "NAME\JOHN PHONE\555444333"

"NAME" and "PHONE" will be unique so anytime i change the proper field i want to change the name or phone inside this textview.

let's for example change JOHN for CLOE with the code

txtOther.text = txtOther.text.replacingOccurrences(of: "NAME(.*?)\\s", with: "NAME\\\(new_value) ", options: .regularExpression)
print (string)

output: "NAMECLOE " instead of "NAME\CLOE "

I can't get the backslash to get print according to the regular expression.

Or maybe change the regex expression just to change JOHN for CLOE after "NAME"

Thanks!!!

Ariel

2 Answers

You can solve this by using a raw string for your regular expresion, that is a string surrounded with #

let pattern = #"(NAME\\)(.*)\s"# 

Note that name and the \ is in a separate group that can be referenced when replacing

let output = string.replacingOccurrences(of: pattern, with: "$1\(new_value) ", options: .regularExpression)

Use

"NAME\\JOHN PHONE\\555444333".replacingOccurrences(
    of: #"NAME\\(\S+)"#, 
    with: "NAME\\\\\(new_value)",
    options: .regularExpression
)

Double backslashes in the replacement, backslash is a special metacharacter inside a replacement.

\S+ matches one or more characters different from whitespace, this is shorter and more efficient than .*?\s, and you do not have to worry about how to put back the whitespace.

Related