假设我有一个字符串,它包含以下内容:
string mystr = "*myid*-myemail-:mypwd:*myid2*-myemail2-:mypwd2:*myid3*-myemail3-:mypwd3:";
我想获得每个具有"*"的子字符串,然后将它们添加到一个新字符串中,然后获得每个具有与具有"-"的值相同的":"的值,所以我尝试了使用split方法,但它不起作用。
string mystr = "*myid*-myemail-:mypwd:*myid2*-myemail2-:mypwd2:*myid3*-myemail3-:mypwd3:";
string[] myid = mystr.Split('*');
string[] myemail = mystr.Split('-');
string[] mypwd = mystr.Split(':');
string ids = "";
string emails = "";
string pwds = "";
foreach (string k in myid)
{
Console.WriteLine("THESE ARE THE IDS");
Console.WriteLine(k);
}
foreach (string k in myemail)
{
Console.WriteLine("THESE ARE THE EMAILS");
Console.WriteLine(k);
}
foreach (string k in mypwd)
{
Console.WriteLine("THESE ARE THE PASSWORDS");
Console.WriteLine(k);
}
这是控制台输出:
THESE ARE THE IDS
THESE ARE THE IDS
myid
THESE ARE THE IDS
-myemail-:mypwd:
THESE ARE THE IDS
myid2
THESE ARE THE IDS
-myemail2-:mypwd2:
THESE ARE THE IDS
myid3
THESE ARE THE IDS
-myemail3-:mypwd3:
THESE ARE THE EMAILS
*myid*
THESE ARE THE EMAILS
myemail
THESE ARE THE EMAILS
:mypwd:*myid2*
THESE ARE THE EMAILS
myemail2
THESE ARE THE EMAILS
:mypwd2:*myid3*
THESE ARE THE EMAILS
myemail3
THESE ARE THE EMAILS
:mypwd3:
THESE ARE THE PASSWORDS
*myid*-myemail-
THESE ARE THE PASSWORDS
mypwd
THESE ARE THE PASSWORDS
*myid2*-myemail2-
THESE ARE THE PASSWORDS
mypwd2
THESE ARE THE PASSWORDS
*myid3*-myemail3-
THESE ARE THE PASSWORDS
mypwd3
THESE ARE THE PASSWORDS
这就是我想要的样子:
THESE ARE THE PASSWORDS
mypwd
mypwd2
mypwd3
THESE ARE THE EMAILs
myemail
myemail2
myemail3
THESE ARE THE IDS
myid
myid2
myid3
您可以使用正则表达式进行以下操作:
string mystr = "*myid*-myemail-:mypwd:*myid2*-myemail2-:mypwd2:*myid3*-myemail3-:mypwd3:";
var matches = Regex.Matches(mystr, @"*(?<Id>[^*]+)*-(?<Email>[^-]+)-:(?<Password>[^:]+):");
然后,您可以按以下方式访问匹配项:
foreach (Match match in matches)
{
Console.WriteLine("Id=" + match.Groups["Id"].Value);
Console.WriteLine("Email=" + match.Groups["Email"].Value);
Console.WriteLine("Password=" + match.Groups["Password"].Value);
}
或者,如果您想将ID、电子邮件和密码分组在一起,请使用:
var ids = matches.OfType<Match>().Select(m => m.Groups["Id"].Value);
var emails = matches.OfType<Match>().Select(m => m.Groups["Email"].Value);
var passwords = matches.OfType<Match>().Select(m => m.Groups["Password"].Value);
foreach (string id in ids)
Console.WriteLine(id);
foreach (string email in emails)
Console.WriteLine(email);
foreach (string password in passwords)
Console.WriteLine(password);
在线试用。
但是,请注意,这可能会中断,因为电子邮件地址可能包含连字符,密码可能包含冒号。在这种情况下,您需要为输入文本提供一种更健壮的格式。