我想用 M
替换没有后跟 pt
的“整个”十进制数字。
例如我需要替换1
、12
和36.7
,而不是45.63
关注。
string exp = "y=tan^-1(45.63pt)+12sin(-36.7)";
我已经试过了
string newExp = Regex.Replace(exp, @"(\d+\.?\d*)(?!pt)", "M");
它给了
"y=tan^-M(M3pt)+Msin(-M)"
这对我来说确实很有意义,但我需要了解
"y=tan^-M(45.63pt)+Msin(-M)"
最佳答案
正则表达式的问题在于它仍然匹配十进制值 45.63
的一部分,直到倒数第二个十进制数字。一种解决方案是向模式添加负前瞻,以确保我们仅在每个十进制值的实端断言 (?!pt)
。此版本正在运行:
string exp = "y=tan^-1(45.63pt)+12sin(-36.7)";
string newExp = Regex.Replace(exp, @"(\d+(?:\.\d+)?)(?![\d.])(?!pt)", "M");
Console.WriteLine(newExp);
打印出来:
y=tan^-M(45.63pt)+Msin(-M)
这里是使用的正则表达式模式的解释:
( match and capture:
\d+ one or more whole number digits
(?:\.\d+)? followed by an optional decimal component
) stop capturing
(?![\d.]) not being followed by another digit or dot
(?!pt) not followed by pt
关于c# - 正则表达式替换 'whole' 十进制数字后不跟某个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65758521/