字符串替换正则表达式

时间:2015-10-06 00:09:02

标签: 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:NSStringCompareOptions.RegularExpressionSearch, range:nil)


print(newString)

更换后我想要的是:

  

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

我得到的是:

  

" * + 3 + x2 + *)"

1 个答案:

答案 0 :(得分: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\)\(?=\\\(\)