c#如何在字符串中找到负值并转换它?

  • 本文关键字:转换 字符串 c# string
  • 更新时间 :
  • 英文 :


我得到这样的字符串:

[(0 +-0,01)*(0,724-0) +(-0,01 +-17,982)*(0,725-0,724) +(-17,982 +-17,983)*(1,324-0,725) +(-17,983 +-30,587)*(1,323-1,324) +(-30,587 +-30,587)*(-0,004-1,323) +(-30,587 +0)*(0--0,004)]*0,5

我必须以一种方式转换——xx,xx或+-xx,xx将在括号中设置-(-xx,xx)或+(-xx,xx)

:

[(0 +(-0,01))*(0,724-0) +(-0,01 +(-17,982))*(0,725-0,724) +(-17,982 +(-17,983))*(1,324-0,725) +(-17,983 +(-30,587))*(1,323-1,324) +(-30,587 +(-30,587))*(-0,004-1,323) +(-30,587 +0)*(0-(-0,004))]*0,5

但是我不知道该怎么做。

您可以尝试正则表达式,例如

using System.Text.RegularExpressions;
... 
string source =
"[(0 +-0,01)*(0,724-0) +(-0,01 +-17,982)*(0,725-0,724) +(-17,982 +-17,983)*(1,324-0,725) +(-17,983 +-30,587)*(1,323-1,324) +(-30,587 +-30,587)*(-0,004-1,323) +(-30,587 +0)*(0--0,004)]*0,5";
string result = Regex.Replace(source, @"(?<=[+-])-[0-9]+(,[0-9]+)?", "($&)");
Console.Write(result);

结果:

[(0 +(-0,01))*(0,724-0) +(-0,01 +(-17,982))*(0,725-0,724) +(-17,982 +(-17,983))*(1,324-0,725) +(-17,983 +(-30,587))*(1,323-1,324) +(-30,587 +(-30,587))*(-0,004-1,323) +(-30,587 +0)*(0-(-0,004))]*0,5

这里我们寻找(?<=[+-])-[0-9]+(,[0-9]+)?模式:

(?<=[+-]) - look ahead for + or -
- - "-" 
[0-9]+ - one or more digit in 0..9 range - integer part
(,[0-9]+)? - optional fractional part: comma then one or more digit in 0..9 range

我们将每个匹配包入(..)-"($&)"

最新更新