0

I simply need to replace:

<p>, <div>

with

\n<p>, \n<div>

in string with one single pattern replacing. Is it possible?

let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>", with: "\n<p>").replacingOccurrences(of: "<div>", with: "\n<div>")

is there a better solution with regex?

2
  • that seems to me a static seek-and-replace procedure of 2 values – why would you think you may need a reg-exp for a better solution (whatever that actually means in this context)? Commented Sep 19, 2018 at 7:53
  • I need to replace the following tags: p, div, ul, li, h1, h2 with \n{tag}. Commented Sep 19, 2018 at 7:55

1 Answer 1

5

You can do a regular expression search, with a template in the replacement string:

let string = "<p>hello</p> my <div>Doggy</div>"
let newString = string.replacingOccurrences(of: "<p>|<div>", with: "\n$0", options: .regularExpression)

For each match, the $0 template is replaced by what actually matched the pattern.

Sign up to request clarification or add additional context in comments.

1 Comment

As always, you are genius;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.