1

I am trying to replace text in string using regex. I accomplished it in c# using the same pattern but in swift its not working as per needed.

Here is my code:

var pattern = "\\d(\\()*[x]"

let oldString = "2x + 3 + x2 +2(x)"

let newString = oldString.stringByReplacingOccurrencesOfString(pattern, withString:"*" as String, options:NSStringCompareOptions.RegularExpressionSearch, range:nil)


print(newString)

What I want after replacement is :

"2*x + 3 +x2 + 2*(x)"

What I am getting is :

"* + 3 + x2 +*)"

1 Answer 1

1
Try this:

(?<=\d)(?=x)|(?<=\d)(?=\()

This pattern matches not any characters in the given string, but zero width positions in between characters.

For example, (?<=\d)(?=x) This matches a position in between a digit and 'x'

(?<= is look behind assertion (?= is look ahead.

(?<=\d)(?=\()    This matches the position between a digit and '('

So the pattern before escaping:

(?<=\d)(?=x)|(?<=\d)(?=\()

Pattern, after escaping the parentheses and '\'

\(?<=\\d\)\(?=x\)|\(?<=\\d\)\(?=\\\(\)
Sign up to request clarification or add additional context in comments.

Comments

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.