简体   繁体   English

C#使用RegEx提取字符串的两个元素

[英]C# extract two elements of a string using a RegEx

I've got the following string which I extracted from a POST request using .Split() . 我有以下字符串,是使用.Split()POST请求中提取的。

I need to extract the e-mail ( login_email= ) and the password ( login_password= ). 我需要提取电子邮件( login_email= )和密码( login_password= )。

login_cmd=&login_params=&login_email=my%40mail.de&login_password=TOPsecret&submit..........

All in all I need to get: 总而言之,我需要获得:

my%40mail.de

TOPsecret

Is there an easy way, maybe without using RegEx, or is writing a RegEx for this easy to learn? 是否有一种简单的方法,也许不使用RegEx,还是正在编写一个易于学习的RegEx? I know the RegEx for extracting the e-mail address should start after login_email= and stop at the & sign. 我知道用于提取电子邮件地址的RegEx应该在login_email=之后开始,并在&符号处停止。

I would say the easiest is to not use regex, but use the built in HttpUtility: 我会说最简单的是不使用正则表达式,而使用内置的HttpUtility:

string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("login_email");

Simples. 简单。

Use lookarounds like below. 使用类似下面的外观。

(?<=login_(?:email|password)=)[^&]*(?=&)

OR 要么

(?<=login_(?:email|password)=)[^&]*

Lookafter to login_email= or login_password and match any character but not of & zero or more times. 照看login_email =或login_password并匹配任何字符,但不匹配&零次或多次。

String input = @"login_cmd=&login_params=&login_email=my%40mail.de&login_password=TOPsecret&submit..........";
Regex rgx = new Regex(@"(?<=login_(?:email|password)=)[^&]*");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);

IDEONE 爱迪生

String input = @"login_cmd=&login_params=&login_email=my%40mail.de&login_password=TOPsecret&submit..........";

Regex rgx = new Regex(@"(?<=login_email=)([^&]+)|(?<=login_password=)([^&]+)");

foreach (Match m in rgx.Matches(input))
{
    if(!m.Groups[1].Value.ToString().Equals(string.Empty))
    {
        Console.WriteLine("Email : " + m.Groups[1].Value);
    }
        if(!m.Groups[2].Value.ToString().Equals(string.Empty))
    {
        Console.WriteLine("Password : " + m.Groups[2].Value);
    }
}

IDEONE 爱迪生

(?<=login_email=)[^&]+|(?<=login_password=)[^&]+

Try this.See demo. 试试看。看演示。

http://regex101.com/r/hQ9xT1/16 http://regex101.com/r/hQ9xT1/16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM