c# - 我需要一些文本解析帮助(正则表达式/C#)

标签 c# .net regex text-parsing

我可以借助适当的正则表达式将以下字符串解析为 3 个变量。带有注释的部分 //TODO: 是我需要正则表达式帮助的地方。现在我刚刚分配了一个静态值,但需要用解析示例文本的真实正则表达式替换它。谢谢!

// This is what a sample text will look like.
var text = "Cashpay @username 55 This is a sample message";

// We need to parse the text into 3 variables.
// 1) username - the user the payment will go to.
// 2) amount - the amount the payment is for.
// 3) message - an optional message for the payment.
var username = "username"; // TODO: Get the username value from the text.
var amount = 55.00; // TODO: Get the amount from the text.
var message = "This is a sample message"; // TODO: Get the message from the text.

// now write out the variables
Console.WriteLine("username: " + username);
Console.WriteLine("amount: " + amount);
Console.WriteLine("message: " + message);

最佳答案

您可以使用捕获组:

var regex = new Regex(@"^Cashpay\s+@([A-Za-z0-9_-]+)\s+(\d+)\s+(.+)$");
var text = "Cashpay @username 55 This is a sample message";

var match = regex.Match(text);

if (!match.Success)
    //Bad string! Waaaah!

string username = match.Groups[1].Value;
int amount = int.Parse(match.Groups[2].Value);
string message = match.Groups[3].Value;

关于c# - 我需要一些文本解析帮助(正则表达式/C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5849704/

相关文章:

c# - 在 Unity : Best practice 中解析类型时传递构造函数参数

.net - 将应用程序更新部署到多个站点

.net - 如何编码以在对话中对电子邮件进行分组

c# - 如果发生对静态记录器的调用,如何进行单元测试

javascript - 匹配没有标签内容的 HTML 文本

regex - 如何使正则表达式匹配的一部分成为可选?

java - 如何将此日期格式与正则表达式相匹配?

c# - 合并 2 个数据表

c# - 如何循环从同一个数组中删除一个值的所有实例?

C# 正则表达式 匹配整个单词,包含特殊字符