[英]Regex for currency and amount C#
我正在尝试为以下输出创建一个正则表达式:
Text - Output Expected
$200 currency sign = "$" and amount = 200
€ 20.34 currency sign = "€" and amount = 20.34
£ 190,234 currency sign = "£" and amount = 190234
$ 20.34 currency sign = "$" and amount = 20.34
我对正则表达式不好,但我仍然想对正则表达式执行此操作。 有人可以帮助我实现这一目标吗?
您可以使用正则表达式:
(\D)\s*([.\d,]+)
caputre组1将包含货币符号和组2 contians值
参见演示http://regex101.com/r/eV2uZ7/1
EXPLANTION
(\\D)
除数字以外的其他任何内容
\\s*
匹配任意数量的空格。
[.\\d,]+
匹配数字,逗号和点。
更具体地说,您还可以指定\\d[.\\d,]*
,以确保值部分始终以数字开头
([$€£]) *([0-9.,]*)
捕获组1将是货币符号,捕获组2将是金额,您还需要用Replace(',','')删除“,”
string str = string.Empty , outPut = string.Empty;
Regex paternWithDot = new Regex(@"\d+(\.\d+)+");
Regex paternWithComa = new Regex(@"\d+(\,\d+)+");
Match match = null;
str = "& 34.34";
if (str.Contains(".")) match = paternWithDot.Match(str);
if (str.Contains(",")) match = paternWithComa.Match(str);
outPut += string.Format( @" currency sign = ""{0}"" and amount = {1}" , str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;
str = "€ 20.34 ";
if (str.Contains(".")) match = paternWithDot.Match(str);
if (str.Contains(",")) match = paternWithComa.Match(str);
outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;
str = "£ 190,234";
if (str.Contains(".")) match = paternWithDot.Match(str);
if (str.Contains(",")) match = paternWithComa.Match(str);
outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;
str = "$ 20.34 ";
if (str.Contains(".")) match = paternWithDot.Match(str);
if (str.Contains(",")) match = paternWithComa.Match(str);
outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;
MessageBox.Show(outPut);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.