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

本文关键字:帮助 正则表达式 文本 | 更新日期: 2023-09-27 17:53:58

我可以使用适当的正则表达式来帮助将下面的字符串解析为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);

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

您可以使用捕获组:

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;

此方法不进行输入验证;在某些情况下,这可能是可以的(例如,输入来自已经经过验证的来源)。如果您是从用户输入中获取这些信息,那么您可能应该使用更健壮的方法。如果它来自一个受信任的来源,但有多种格式(例如:"Cashpay"是众多选择之一)你可以在分割后使用switch或if语句进行流控制:

// make sure you validate input (coming from trusted source?) 
// before you parse like this.
string list[] = text.Split(new char [] {' '});
if (list[0] == "Cashpay")
{
    var username = list[1].SubString(1);
    var amount = list[2];
    var message = string.Join(' ',list.Skip(3));
}

// make sure you validate input (coming from trusted source?) 
// before you parse like this.
string list[] = text.Split(new char [] {' '},4);
if (list[0] == "Cashpay")
{
    var username = list[1].SubString(1);
    var amount = list[2];
    var message = list[3];
}