微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符串替换和拆分

如何解决字符串替换和拆分

如何使用单个 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 $

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。