简体   繁体   中英

C# Find and replace a price in a long string

I have a long string representing a web page in html, I have to change the price of a product detail, the string to be replaced would be like this: 10.20 € or 100.22 € or 1.50 € etc. the price may vary so the replace must work with any amount. How can I find and replace this price? The only code I found is this:

Regex.Replace(input, "[0-9].[0-9][0-9]", "");

but it is not based on the € symbol and therefore could find other similar numbers in the string and replace them and especially if in case there is a number with more digits it does not replace all the digits thanks you

Solution by @Kenny:

var output = Regex.Replace(input, "[0-9]*.[0-9]* €", "");

thanks

If you are deadset on using a REGEX, all you would have to do is add a positive lookahead to your existing regex. It would look like this:

Regex.Replace(input, "[0-9]*.[0-9][0-9](?=\s€)", "");

As you can see, the (?=\\s€) Checks to make sure that a euro symbol is present. To experiment more with regexes, you can use this website: regexr.com

The above answer also is dependant on how your HTML euro characters are encoded. You should check we're matching the right one!

You may use

var output = Regex.Replace(input, @"[0-9]+(?:\.[0-9]+)?\s*€", "");

Details

  • [0-9]+ - 1+digits
  • (?:\\.[0-9]+)? - an optional substring matching
    • \\. - a dot (it must be escaped to match a literal dot)
    • [0-9]+ - 1+ digits
  • \\s* - 0+ whitespaces
  • - an euro sign.

See the .NET regex demo .

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