2015-10-06 197 views
1

我想用正則表達式替換字符串中的文本。我用c#完成它使用相同的模式,但在迅速不按需要工作。字符串替換正則表達式

這裏是我的代碼:

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
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\)\(?=\\\(\)