簡體   English   中英

c#如何在字符串中找到負值並轉換它?

[英]c# how to find negative values in string and convert it?

我得到這樣的字符串:

[(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

我們包裝成(..) - "($&)"每個匹配項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM