我的字符串:
string str = "user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname";
现在我想用正则表达式得到值:
var reg = Regex.Matches(str, @"user:(.+?)\sid:(\d+)\s+nickname:(.+?)")
.Cast<Match>()
.Select(a => new
{
user = a.Groups[1].Value,
id = a.Groups[2].Value,
nickname = a.Groups[3].Value
})
.ToList();
foreach (var ca in reg)
{
Console.WriteLine($"{ca.user} id: {ca.id} nickname: {ca.nickname}");
}
我不知道如何使用正则表达式来实现 nickname:(the nickname)
我只想使用昵称,如果它有一个像 nickname:kevo200
和 noch 昵称
最佳答案
我不是 100% 确定这是否回答了您的问题,但我通过正则表达式解析从给定的输入字符串中获取了一个列表,并在可用时返回昵称或否则返回用户名。
PS C:\WINDOWS\system32> scriptcs
> using System.Text.RegularExpressions;
> var regex = new Regex(@"\|?(?:user(?::?(?<user>\w+))\sid(?::?(?<id>\d*))\s?nickname(?::?(?<nick>\w+))?)");
> var matches = regex.Matches("user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname");
> matches.Cast<Match>().Select(m=>new {user=m.Groups["user"].Value,nick=m.Groups["nick"].Value}).Select(u=>string.IsNullOrWhiteSpace(u.nick)?u.user:u.nick);
[
"steo",
"kevo200",
"noko"
]
编辑:正则表达式设计器:https://regexr.com/3uf8t
编辑:改进版本以接受昵称中的转义序列
PS C:\WINDOWS\system32> scriptcs
> using System.Text.RegularExpressions;
> var regex = new Regex(@"\|?(?:user(?::(?<user>\w+))?\sid(?::(?<id>\d*))?\s?nickname(?::(?<nick>[\w\\]+))?)");
> var matches = regex.Matches("user:steo id:1 nickname|user:kevo id:2 nickname:kevo200|user:noko id:3 nickname|user:kevo id:2 nickname:kev\\so200");
> matches.Cast<Match>().Select(m=>new {user=m.Groups["user"].Value,nick=m.Groups["nick"].Value.Replace("\\s"," ")}).Select(u=>string.IsNullOrWhiteSpace(u.nick)?u.user:u.nick);
[
"steo",
"kevo200",
"noko",
"kev o200"
]
关于c# - 正则表达式字符串,但有几个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016353/