2010-11-08 30 views
4

我試圖從字符串值中刪除任何貨幣符號。正則表達式從字符串中移除任何貨幣符號?

using System; 
using System.Windows.Forms; 
using System.Text.RegularExpressions; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     string pattern = @"(\p{Sc})?"; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      decimal x = 60.00M; 
      txtPrice.Text = x.ToString("c"); 
     } 

     private void btnPrice_Click(object sender, EventArgs e) 
     { 
      Regex rgx = new Regex(pattern); 
      string x = rgx.Replace(txtPrice.Text, ""); 
      txtPrice.Text = x; 
     } 
    } 
} 
// The example displays the following output: 
// txtPrice.Text = "60.00"; 

這可行,但它不會刪除阿拉伯語中的貨幣符號。我不知道爲什麼。

以下是帶貨幣符號的示例阿拉伯字符串。

txtPrice.Text = "ج.م.‏ 60.00"; 
+0

您是否在表達式中嘗試過使用'CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol'? – 2010-11-08 01:21:16

+0

@mootinator,你看到單詞'any'嗎?您的解決方案將只取代'當前'貨幣符號 – 2011-12-09 10:01:00

+5

@ taras.roshko您在評論發佈13個月後是否養成了諷刺言論的習慣?顯然有一個原因是評論而不是答案。 – 2011-12-09 15:13:49

回答

9

不符合符號 - 使表達式匹配數字。

嘗試這樣:

([\d,.]+) 

有太多的考慮到貨幣符號。最好只捕獲你想要的數據。前面的表達式將捕獲數字數據和任何地方分隔符。

使用這樣的表達:

var regex = new Regex(@"([\d,.]+)"); 

var match = regex.Match(txtPrice.Text); 

if (match.Success) 
{ 
    txtPrice.Text = match.Groups[1].Value; 
} 
+0

這是錯誤的輸出是txtPrice.Text =「جم」; – 2010-11-08 01:30:21

+0

請參閱我的示例代碼 - 您不希望使用Regex.Replace這個表達式。 – 2010-11-08 01:40:57

+0

private void Form1_Load(object sender,EventArgs e) decimal x = 60.00M; txtPrice.Text = x.ToString(「c」); } private void btnPrice_Click(object sender,EventArgs e) { string pattern = @「([\ d,。] +)」; Regex rgx = new Regex(pattern); string x = rgx.Replace(txtPrice.Text,「」); txtPrice.Text = x; } – 2010-11-08 01:45:05

0

從安德魯野兔的答案几乎是正確的,你可以隨時使用\ d匹配數字*,它將任何數字匹配問題文本。

相關問題