Regex 正则表达式中的字符串替换

Regex 正则表达式中的字符串替换,regex,swift2,xcode7,Regex,Swift2,Xcode7,我试图用正则表达式替换字符串中的文本。我用c#完成了它,使用了相同的模式,但在swift中,它没有按照需要工作 这是我的密码: var pattern = "\\d(\\()*[x]" let oldString = "2x + 3 + x2 +2(x)" let newString = oldString.stringByReplacingOccurrencesOfString(pattern, withString:"*" as String, options:NSStringCompa

我试图用正则表达式替换字符串中的文本。我用c#完成了它,使用了相同的模式,但在swift中,它没有按照需要工作

这是我的密码:

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)
更换后我想要的是:

“2*x+3+x2+2*(x)”

我得到的是:

“*+3+x2+*)”

试试这个:
(?
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\)\(?=\\\(\)