天天看點

好用的正規表達式

1。 string s = "某某的面積是12345678平方米"; string t = Regex.Replace(s, @"(?<=/d)(?=(/d/d/d)+(?!/d))", ","); // 同理,這個正則的作用是把一串數字每3位加一個逗号。 Console.WriteLine(t); // 輸出:某某的面積是12,345,678平方米

2。

string s = "1234567890";

// 考慮了一下,這樣更簡單:

string t = Regex.Replace(s, "(?!^)(?=(?:.{4})+$)", " ");

// 把一個字元串從右往左每4位加一個空格,結果是:"12 3456 7890"

3。

using System;

using System.Text.RegularExpressions;

class Program

{

  // 把阿拉伯數字的金額轉換為中文大寫數字

  static string ConvertToChinese(double x)

  {

    string s = x.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");

    string d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L/.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[/.]|$))))", "${b}${z}");

    return Regex.Replace(d, ".", delegate(Match m) { return "負元空零壹貳叁肆伍陸柒捌玖空空空空空空空分角拾佰仟萬億兆京垓秭穰"[m.Value[0] - '-'].ToString(); });

  }

  static void Main()

  {

    Random r = new Random();

    for (int i = 0; i < 10; i++)

    {

      double x = r.Next() / 100.0;

      Console.WriteLine("{0,14:N2}: {1}", x, ConvertToChinese(x));

    }

  }

}

繼續閱讀