2011-05-01 45 views
1

我可以使用适当的正则表达式的一些帮助来解析下面的字符串到3个变量。有评论说// TODO:的部分是我需要正则表达式帮助的地方。现在我刚刚分配了一个静态值,但需要用解析示例文本的真正正则表达式来替换它。谢谢!我需要一些文本解析帮助(正则表达式/ C#)

// 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); 
+0

你甚至试过了吗?有很多用于构建Regexes的好工具,例如[Expresso](http://www.ultrapico.com/Expresso.htm)或[Regex Buddy](http://www.regexbuddy.com/)。 – Lucero 2011-05-01 16:36:37

+0

我在正则表达式方面遇到了挑战:-)我一直在做一些像text.substring(0,text.indexOf('@'....)的东西,你甚至不想看到,我是寻找一些干净的表达,这些人真的很擅长这个东西 – 2011-05-01 16:41:49

+1

我链接的工具可以帮助你建立表达式,通过使用它们,你应该没有问题做你需要做的解析这些简单的字符串,我更喜欢正则表达式“手动”解析,因为这允许您声明性地定义要匹配的模式,而不是强制搜索部分;从而使用正则表达式“免费”输入验证(如果模式不匹配,则输入无效) – Lucero 2011-05-01 16:45:59

回答

4

您可以使用捕获组:

var regex = new Regex(@"^Cashpay\[email protected]([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; 
+0

我喜欢'抛出新的异常(“Waaaah!”) – Hogan 2011-05-01 16:49:08

+0

@Hogan:http://msdn.microsoft.com/en-us/library/ms182338.aspx – SLaks 2011-05-01 16:52:43

+0

@ SLacks:公平点它应该是'FormatException'或'SLaksException'。 – Hogan 2011-05-01 17:04:27

3

此方法不执行输入验证;在某些情况下,这可能是好的(例如输入来自已经验证的源)。如果你从用户输入中得到这个,你应该使用一个更健壮的方法。如果是来自可靠来源来,但有多种格式(例如,“Cashpay”是众多选择之一),你可以使用一个开关或者语句拆分后流量控制:

// 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]; 
} 
+0

不错,简单。唯一的问题是当使用list [3]时,消息会被截断,因为它中有一个空格。 – 2011-05-01 16:37:32

+0

'message = String.Join(“”,list.Skip(3))''。请注意,你应该'StringSplitOptions.RemoveEmptyEntries'。 – SLaks 2011-05-01 16:38:06

+0

但是,按原样它将无法解析消息,并且您没有验证内置输入。这种类型的代码会在分割之后的某个地方抛出'IndexOutOfRangeException',这并不是处理无效输入的好方法。 – Lucero 2011-05-01 16:39:55