【问题标题】:I need some Text Parsing Help (Regular Expressions / C#)我需要一些文本解析帮助(正则表达式/C#)
【发布时间】:2011-05-01 16:30:58
【问题描述】:

我可以使用一些正确的正则表达式帮助将以下字符串解析为 3 个变量。 cmets 说// 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);

【问题讨论】:

  • 你试过了吗?有很多构建正则表达式的好工具,例如ExpressoRegex Buddy
  • 我在正则表达式方面遇到了挑战 :-) 我一直在做类似 text.substring(0, text.indexOf('@'....想看看。我正在寻找真正擅长这些东西的人的一些干净的表达方式。
  • 我链接的工具可以帮助您构建表达式,通过使用它们,您在解析这些简单字符串时应该没有问题。我更喜欢正则表达式而不是“手动”解析,因为这允许您以声明方式定义要匹配的模式,而不是强制搜索部分;因此,您可以使用正则表达式“免费”获得输入验证(如果模式不匹配,则输入无效)。

标签: c# .net regex text-parsing


【解决方案1】:

您可以使用捕获组:

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;

【讨论】:

  • 我喜欢throw new Exception("Waaaah!")
  • @SLacks:公平点应该是FormatExceptionSLaksException
  • 很好,如果 int 应该是货币值,则只有 int 应该是 double 或 decimal。
【解决方案2】:

此方法不进行输入验证;在某些情况下,这可能没问题(例如,输入来自已经过验证的来源)。如果您从用户输入中获取此信息,您可能应该使用更强大的方法。如果它来自受信任的来源但有多种格式(例如“现金支付”是众多选择之一),您可以在拆分后使用 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];
}

【讨论】:

  • 漂亮而简单。唯一的问题是使用 list[3] 时消息会被截断,因为其中有一个空格。
  • message = String.Join(" ", list.Skip(3))。请注意,您应该StringSplitOptions.RemoveEmptyEntries
  • 但是它将无法解析消息,并且您没有对内置输入的验证。这种代码会在拆分后的某个地方抛出IndexOutOfRangeException,这并不是处理无效输入的好方法。
  • @Slack -- 喜欢你的比我加入 4 参数更好。
  • @SLaks, @Hogan:为什么不使用Split 的正确重载,而不是在最后合并消息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 2012-11-30
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
相关资源
最近更新 更多