我想知道如何从用户发送的消息中拆分特定的字符串 消息看起来像这样
"username: @newbie <----- need to recive the all string with the '@'
password: 1g1d91dk
uid: 961515154 <-- always string of 9 numbers
message: blablabla < ---- changing anytime how can i recive the string after message:"
date: 30/06/18"
mnumer: 854762158 <-- always string of 9 numbers to but i want to upper one
我的意思是在“ uid:”之后获得 9 个数字?
非常感谢! 我发现了一个类似的问题,但都没有回答我的问题 抱歉,我的英语不是我的母语。
答案 0 :(得分:2)
您是否可以简单地用新行.Split('\n')
分割字符串,这将给您一个string[]
,然后在每个元素中将其用':'
分割,然后读取第二个值?如果您需要在第一位进行引用,可以将其存储在Dictionary<string, string>
中
string inString = @"username: @newbie
password: 1g1d91dk
uid: 961515154
message: blablabla
date: 30/06/18
mnumer: 854762158";
string[] lines = inString.Split('\n');
Dictionary<string, string> data = new Dictionary<string, string>();
foreach (string line in lines)
{
// There are two ways to avoid splitting multiple : and just using the first
// Here is my way
string[] keyValue = line.Split(':');
data.Add(keyValue[0].Trim(), string.Join(':', keyValue.Skip(1).ToArray()).Trim());
// Here is another way courtesy of: Dmitry Bychenko
string[] keyValue = line.Split(new char[] {':'}, 2);
data.Add(keyValue[0].Trim(), keyValue[1].Trim());
}
这将为您提供一个字典,您可以在其中从第一部分开始访问字符串的每个部分的值。
不知道您的用法是什么,但这会有所帮助。
您可以通过执行uid
来获得data["uid"]
答案 1 :(得分:1)
尝试使用正则表达式:
string source =
@"username: @newbie <----- need to recive the all string with the '@'
password: 1g1d91dk
uid: 961515154 <-- always string of 9 numbers
message: blablabla < ---- changing anytime how can i recive the string after message:"
date: 30/06/18"
mnumer: 854762158 <-- always string of 9 numbers to but i want to upper one";
string result = Regex.Match(source, @"(?<=uid:\s*)[0-9]{9}").Value;
如果uid:
应该开始行
string result = Regex.Match(
source,
@"(?<=^uid:\s*)[0-9]{9}",
RegexOptions.Multiline).Value;
答案 2 :(得分:0)
您可以使用正则表达式来匹配文本值中的模式,并获取所需的值。例如,尝试:
var regex = new Regex(@"^(uid:\s)([0-9]+)");
var match = regex.Match("uid: 961515154");
Console.WriteLine(match.Groups[1].Value); // you should get : 961515154
答案 3 :(得分:0)
与@ZachRossClyne类似的方法:
void Main()
{
var data = @"username: @newbie
password: 1g1d91dk
uid: 961515154
message: blablabla
date: 30 / 06 / 18
mnumer: 854762158";
var regex = new Regex(@"^\s*(?<key>[^\:]+)\:\s*(?<value>.+)$");
var dic = data
.AsLines()
.Select(line => regex.Match(line))
.Where(m => m.Success)
.Select(m => new { key = m.Groups["key"].Value, value = m.Groups["value"].Value })
.ToDictionary(x => x.key, x => x.value);
Console.WriteLine(dic["uid"]);
}
public static class StringEx
{
public static IEnumerable<string> AsLines(this string input)
{
string line;
using(StringReader sr = new StringReader(input))
while ((line = sr.ReadLine()) != null)
{
yield return line;
}
}
}