Replace regex \\+n from string in swift

Viewed 139

i want to remove every string starts with one or more \ and follow with n. For example: input: {\n\n abc \\nb\\\ncc} expect output: { abc bcc} In javascript it works with regex /\\+n/g But it doesn't work in swift:

str.replacingOccurrences(of: "\\+n", with: "", options: .regularExpression)
1 Answers

To remove all ns that contain one or more backslashes in front, and all newlines with any amount of backslashes in front, you can use

#"\\+n|\\*\n"#

Note the # before and after the double quotes mean that the literal is a raw string literal where backslashes are treated as literal backslashes and do not form string escape sequences, like \n, \t, \r, etc.

Here, the pattern means

  • \\+n - one or more backslashes followed with n
  • | - or
  • \\*\n - zero or more backslashes followed with a newline.

Note that here, \n is a regex escape matching a newline, it is not an LF, \x0A character.

Related