2008-10-08 158 views

回答

45

答案很簡單,適用於至少有幾千個字符的字符串。

實施例1:

Regex rx = new Regex(@"\\[uU]([0-9A-F]{4})"); 
result = rx.Replace(result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString()); 

實施例2:

Regex rx = new Regex(@"\\[uU]([0-9A-F]{4})"); 
result = rx.Replace(result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); }); 

第一個例子示出了使用一個lambda表達式(C#3.0)和第二所取得的替換使用委託它應與工作C#2.0。

要打破這是怎麼回事就在這裏,我們首先創建一個正則表達式:

new Regex(@"\\[uU]([0-9A-F]{4})"); 

然後我們調用替換()以字符串「結果」和匿名方法(在第一個例子lambda表達式和第二個委託 - 委託也可以是常規方法),它轉換字符串中找到的每個正則表達式。

Unicode轉義被處理這樣的:

((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); }); 

獲取表示所述逃逸的數目部分(跳過前兩個字符)的字符串。

match.Value.Substring(2) 

解析使用Int32.Parse(),接受字符串並且該parse()函數應該期望在這種情況下是一個十六進制數的數字格式的字符串。

NumberStyles.HexNumber 

然後我們投得到的數字爲Unicode字符:

(char) 

最後,我們調用toString()的Unicode字符這給了我們這是值傳遞迴替換它的字符串表示():

.ToString() 

注意:不能抓住文字,與子串調用你可以使用匹配參數的GroupCollection進行轉換,並在子表達式正則表達式僅捕獲數字('2320'),但這更復雜,可讀性更差。

+2

\ u和\ü應該區別對待 - \ u指定4個十六進制數字(16個比特),其中\ U指定8(32位) - 一個unicode碼點長度爲21位。另外,您應該使用char.ConvertFromUtf32()方法而不是強制轉換。 – 2008-10-08 22:18:13

8

重構多一點:

Regex regex = new Regex (@"\\U([0-9A-F]{4})", RegexOptions.IgnoreCase); 
string line = "..."; 
line = regex.Replace (line, match => ((char)int.Parse (match.Groups[1].Value, 
    NumberStyles.HexNumber)).ToString()); 
0

我想你最好的小寫字母添加到您的正則表達式。它對我更好。

Regex rx = new Regex(@"\\[uU]([0-9A-Fa-f]{4})"); 
result = rx.Replace(result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString()); 
5

這是VB.NET當量:

Dim rx As New RegularExpressions.Regex("\\[uU]([0-9A-Fa-f]{4})") 
result = rx.Replace(result, Function(match) CChar(ChrW(Int32.Parse(match.Value.Substring(2), Globalization.NumberStyles.HexNumber))).ToString()) 
相關問題