正则表达式中的字符串替换
String Replacing in Regex
我正在尝试使用正则表达式替换字符串中的文本。我使用相同的模式在 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\)\(?=\\(\)
我正在尝试使用正则表达式替换字符串中的文本。我使用相同的模式在 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\)\(?=\\(\)