我需要将数量解析为十进制,将货币代码解析为字符串。
输入字符串
302 600.00 RUB
10 000.00 USD
模式是
答案 0 :(得分:1)
这未经过测试,但你可以做这样的事情。
string text = "302 600.00 RUB";
decimal amount;
string type;
var lastspace = text.lastIndexOf(" ");
decimal.TryParse(text.substring(0, lastspace - 1), out amount);
type = text.substring(lastspace + 1);
希望这有帮助。
答案 1 :(得分:1)
using System.Text.RegularExpressions;
[...]
string sInput = "302 10 600.00 RUB";
// string sInput = "302 600.00 RUB";
// string sInput = "10 000.00 USD";
var rgmResult = Regex.Match(sInput, @"^(?<qty>\d+) (?<price>\d{1,3}( \d{3})*\.\d{2}) (?<cur>[A-Z]{3})$");
string sQuantity = rgmResult.Groups["qty"].Value;
string sPrice = rgmResult.Groups["price"].Value;
string sCurrency = rgmResult.Groups["cur"].Value;
答案 2 :(得分:1)
您可以将正则表达式与累加器一起使用,自定义 NumberFormat
string pattern = @"(?<decimal>[0-9]{0,3}(\s[0-9]{3})*(.[0-9]+){0,1})\s" +
@"(?<currency>[a-zA-Z]+){1}";
string input = "302 600.00 RUB\r\n10 000.00 USD";
// Get text that matches regular expression pattern.
MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberDecimalSeparator = ".";
format.NumberDecimalDigits = 2;
Dictionary<string, decimal> dictionary = new Dictionary<string, decimal>();
foreach (Match match in matches)
{
dictionary.Add(match.Groups["currency"].Value, Decimal.Parse(match.Groups["decimal"].Value, format));
}
if (dictionary.Count > 0)
{
foreach (KeyValuePair<string, decimal> item in dictionary)
{
Console.WriteLine("Currency : {0} Amount: {1}", item.Key, item.Value);
}
}
输出是:
Currency : RUB Amount: 302600,00
Currency : USD Amount: 10000,00