问题描述
如何使用单个 Replace & Spit 方法拆分此值
Tel-0190 Texas 2020-12-31 9 890,00 $ 4,00 $ 8 690,00 $
我想像这样拆分字符串结果:
"Tel-0190" "Texas" "2020-12-31" "9 890,00 $" "4,00 $" "8 690,00 $"
我试过了:
str.Replace(" ","_")
.Replace("\d* ","\d* ")
.Replace(" €"," €")
.Split("_"C)
解决方法
尝试使用正则表达式:
private const string Source = "Tel-0190 Texas 2020-12-31 9 890,00 $ 4,00 $ 8 690,00 $";
private const string RegexPattern =
@"(?<tel>Tel-\d+) (?<state>Texas) (?<date>\d{4}-\d{1,2}-\d{1,2}) (?<num1>[0-9,]+[$€]) (?<num2>[0-9,]+[$€]) (?<num3>[0-9,]+[$€])";
我在正则表达式中使用“命名组”。我试图猜测你的规则。此代码将查找组:
var regex = new Regex(RegexPattern);
var match = regex.Match(Source);
if (match != null && match.Groups.Count == 7)
{
var groups = match.Groups;
Debug.WriteLine(groups["tel"]);
Debug.WriteLine(groups["state"]);
Debug.WriteLine(groups["date"]);
Debug.WriteLine(groups["num1"]);
Debug.WriteLine(groups["num2"]);
Debug.WriteLine(groups["num3"]);
}
结果如下:
Tel-0190
Texas
2020-12-31
9 890,00 $
4,00 $
8 690,00 $