简体   繁体   中英

Removing invalid characters from price

I have a scenario where I have to remove certain characters from a price string using 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.

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.

Case 2: if you require number which contains only , following is the regex you can use to extract the same

[0-9,]{1,}

Case 3: if ( is there always there after number, the following regex can be used

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

following is c# code for regex

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,000
  • 3,950,000,000
  • 3,950,000,000,000,000.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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