c# - 正则表达式替换 'whole' 十进制数字后不跟某个字符串

标签 c# regex

我想用 M 替换没有后跟 pt 的“整个”十进制数字。

例如我需要替换11236.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/

相关文章:

c# - 更新 ConcurrentDictionary 中的列表

c# - 我怎样才能获得 DPI 2 不同百分比的监视器?

c# - EF 和 IHostedService 的多个实例

java - 包含单词但不包含其前面的特定单词

swift - 在 swift 中使用 RegExp 降低浮点精度

c# - ProcessCmdKey - 等待 KeyUp?

c# - 当一个线程调用 WaitOne 时,如何找到发回信号的其他线程?

ruby-on-rails - 如果不存在默认协议(protocol),如何在 URL 前面加上默认协议(protocol)?

python - 正则表达式中的灾难性回溯

javascript - 将所有出现的 {{var}} 替换为值