简体   繁体   English

从价格中删除无效字符

[英]Removing invalid characters from price

I have a scenario where I have to remove certain characters from a price string using C#. 我有一种情况,我必须使用C#从价格字符串中删除某些字符。

I'm looking for a regular expression to remove these characters or something better than that. 我正在寻找一个正则表达式来删除这些字符或比这更好的东西。

For example, if the price string is 例如,如果价格字符串是

"3,950,000 ( Ex. TAX )"

I want to remove "( Ex. TAX )" from the string. 我想从字符串中删除"( Ex. TAX )"

Basically I have to remove the any character from string except numbers, dot and comma. 基本上,我必须从字符串中删除任何字符,数字,点和逗号除外。

Regular expressions are always tricky to get right, since the input can vary so greatly, but I think this one covers your needs: 正则表达式总是很棘手,因为输入可能会有很大的不同,但是我认为这可以满足您的需求:

string pattern = @"([\d]+[,.]{0,1})+";
string cleanedPrice = Regex.Match(price, pattern).Value;

Explained: 解释:

(         - start matching group
[\d]+     - match any decimal digit, at least once
[,.]{0,1} - ...followed by 0 or 1 comma or dot
)         - end of group
+         - repeat at least once

简单替换即可使用RegEx吗?

string clean = "3,950,000 ( Ex. TAX )".Replace(" ( Ex. TAX )", string.Empty);

尝试这个

myPrice.Replace(" ( Ex. TAX ),"")
String price = "3,950,000 ( Ex. TAX)".Replace(" ( Ex. TAX)","");

You can use following regular expression 您可以使用以下正则表达式

Case 1: if ( Ex.TAX ) is constant, you can just remove the text using string function String.Replace. 情况1:如果(Ex.TAX)是常数,则可以使用字符串函数String.Replace删除文本。

Case 2: if you require number which contains only , following is the regex you can use to extract the same 情况2:如果您要求仅包含的数字,则可以使用以下正则表达式提取相同的数字

[0-9,]{1,} [0-9,{1,}

Case 3: if ( is there always there after number, the following regex can be used 情况3:如果(数字后面总是有数字,则可以使用以下正则表达式

\\d.*(?=\\() \\ d *(?= \\()

following is c# code for regex 以下是正则表达式的C#代码

public static Regex regex = new Regex(
      "\\d.*(?=\\() ",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );
//// Capture the first Match, if any, in the InputText
// Match m = regex.Match(InputText);

要找到“(例如TAX)”,请尝试以下正则表达式:

/\( Ex\. TAX \)/i
 Regex rex = new Regex(@"(?:(?:\d{1,2},)?(?:\d{3},)*(?:\d{3})(?:\.\d+){0,})|(\d+)");

 Console.WriteLine(rex.Match("3,950,000 ( Ex. TAX )").Groups[0].Captures[0].Value);
 Console.WriteLine(rex.Match("3,950,000,000").Groups[0].Captures[0].Value);
 Console.WriteLine(rex.Match("3,950,000,000UHFWF#FWHFWEFE").Groups[0].Captures[0].Value);
 Console.WriteLine(rex.Match("3,950,000,000,000,000.00").Groups[0].Captures[0].Value);

Output: 输出:

  • 3,950,000 3,950,000
  • 3,950,000,000 39.5亿
  • 3,950,000,000 39.5亿
  • 3,950,000,000,000,000.00 3,950,000,000,000,000.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM