简体   繁体   English

C#查找并替换长字符串中的价格

[英]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. 我有一个用html表示网页的长字符串,我必须更改产品详细信息的价格,要替换的字符串是这样的: 10.20 €100.22 €1.50 €等。价格可能有所不同,因此替换必须工作任何数量。 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: @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. 如果您对使用REGEX不满意,您所要做的就是向现有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. 如您所见, (?=\\s€)检查以确保存在欧元符号。 To experiment more with regexes, you can use this website: regexr.com 要对正则表达式进行更多试验,可以使用以下网站: regexr.com

The above answer also is dependant on how your HTML euro characters are encoded. 上面的答案还取决于HTML欧元字符的编码方式。 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]+ -1+个数字
  • (?:\\.[0-9]+)? - an optional substring matching -可选的子字符串匹配
    • \\. - a dot (it must be escaped to match a literal dot) -一个点(必须转义以匹配文字点)
    • [0-9]+ - 1+ digits [0-9]+ -1+个数字
  • \\s* - 0+ whitespaces \\s* -0+空格
  • - an euro sign. -欧元符号。

See the .NET regex demo . 请参阅.NET regex演示

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

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