日期:2014-05-18  浏览次数:20378 次

【正则】连续相同的数字
例如:
55.0000 替换成55 
55.0600 替换成55.06
55.0678 替换成55.0678 
55.0670 替换成55.0670
55.1000 替换成55.1

C# code

Regex.Replace(s, @"", "", RegexOptions.IgnoreCase);



------解决方案--------------------
帮顶
------解决方案--------------------


Regex.Replace(s, @"(?<=\.\d*)(\d)(\1)+", "").TrimEnd('.');

------解决方案--------------------
C# code
  string tempStr = File.ReadAllText(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312"));
                string pattern = @"\d+(.\d+)?";
                List<float> temp_result = Regex.Matches(tempStr,pattern).Cast<Match>().Select(a=>float.Parse(a.Value)).ToList();
                /*
                          [0]    55.0    float
                        [1]    55.06    float
                        [2]    55.0678    float
                        [3]    55.067    float
                        [4]    55.1    float

                 */

------解决方案--------------------
个人认为,你的问题,就是去除数字多余的0,这用数字好解决这个问题,用正则反而不好解决。

[code=C#]var source = "55.3000";
var result = decimal.Parse(source).ToString("0.0");/code]
------解决方案--------------------
C# code

void Main()
{
    var list=new List<string>{ 
                "55.0000",
                "55.0600",
                "55.0678",
                "55.0670",
                "55.1000"
                };
    var reg=new Regex(@"(?<=\.\d*)(\d)(\1)+");
    list.ForEach(l=>Console.WriteLine("{0}:\t{1}",l,reg.Replace(l,"").TrimEnd(new char[]{'.','0'})));
    /*
    55.0000:    55
    55.0600:    55.06
    55.0678:    55.0678
    55.0670:    55.067
    55.1000:    55.1
    */
}

------解决方案--------------------
探讨

个人认为,你的问题,就是去除数字多余的0,这用数字好解决这个问题,用正则反而不好解决。

[code=C#]var source = "55.3000";
var result = decimal.Parse(source).ToString("0.0");/code]

------解决方案--------------------
其实这根本不需要正则,直接这样即可:

"55.1030".TrimEnd(new char[]{'.','0'})
------解决方案--------------------
忘记了,把格式串换成0.#即可
C# code
var source = "55.3000";
var result = decimal.Parse(source).ToString("0.#");

------解决方案--------------------

------解决方案--------------------
探讨

C# code

void Main()
{
var list=new List<string>{
"55.0000",
"55.0600",
"55.0678",
"55.0670",
"55.1000"
……