C# 在C中的另一个字符串中查找多个值和字符串#
我有一个字符串,有4行:C# 在C中的另一个字符串中查找多个值和字符串#,c#,string,split,C#,String,Split,我有一个字符串,有4行: id score ping guid name lastmsg address qport rate --- ----- ---- ---------- --------------- ------- --------------------- ------ ----- 1 11 45 176387877 Player 1 3250 101.102.103.104:55
id score ping guid name lastmsg address qport rate
--- ----- ---- ---------- --------------- ------- --------------------- ------ -----
1 11 45 176387877 Player 1 3250 101.102.103.104:555 3647 25000
2 23 61 425716719 Player 2 3250 105.106.107.108:555 5978 25000
如何“提取”所有这些值?比如,我想保存“id”、“score”、“ping”、“guid”、“name”等
我在这里找到了一个“GetBetween”函数。我还尝试学习string.Split函数。但我认为我还没有接近我想要归档的内容,而且我还不太理解拆分字符串
我基本上需要删除值之间的所有“”空格,问题是,值的长度可能会更改,例如“name”
有人能给我举个例子,我如何提取这些值吗
提前谢谢 是你的朋友,这很有效
void Main()
{
// fun fact, the @ in front of the string means it's literal, so you
// literally get the new lines
var input =
@"id score ping guid name lastmsg address qport rate
-- - -------------------------------------------------------------------------
1 11 45 176387877 Player 1 3250 101.102.103.104:555 3647 25000
2 23 61 425716719 Player 2 3250 105.106.107.108:555 5978 25000";
//Gets you each line
var lines = input.Split('\n');
// Skip 2 because I doubt you care about the column title
// or the row with the dashes
foreach (var line in lines.Skip(2))
{
// For each line, Regex split will return an array with each entry
// Set a breakpoint with the debugger and inspect to see what I mean.
// Splits using regex - assumes at least 2 spaces between items
// so space in 'Player 1' is handled it's a fickle solution though
// Trim the line before RegEx split to avoid extra data in the split
var r = Regex.Split(line.Trim(), @"\s{2,}");
}
}
您可以使用正则表达式和命名组执行此操作 样本输入
var str = @"id score ping guid name lastmsg address qport rate
--- ----- ---- ---------- --------------- ------- --------------------- ------ -----
1 11 45 176387877 Player 1 3250 101.102.103.104:555 3647 25000
2 23 61 425716719 Player 2 3250 105.106.107.108:555 5978 25000";
正则表达式定义
var regex = new Regex(@"^(?<id>[\d]+)(\s{2,})(?<score>[\d]+)(\s{2,})(?<ping>[\d]+)(\s{1,})(?<guid>[\d]+)(\s{2,})(?<name>([\w]+\s[\w]+))(\s{2,})(?<lastmsg>[\d]+)(\s{2,})(?<ip>[\d.:]+)(\s{2,})(?<port>[\d]+)(\s{2,})(?<rate>[\d]+)$",RegexOptions.Compiled);
输出
ID = 1
Score = 11
Ping = 45
Guid = 176387877
Name = Player 1
Last Msg = 3250
Port = 3647
Rate = 25000
ID = 2
Score = 23
Ping = 61
Guid = 425716719
Name = Player 2
Last Msg = 3250
Port = 5978
Rate = 25000
看起来您可以在空格上拆分第二行并获得每列的长度,然后您可以使用
string.Substring
从每行中提取值,并使用Trim
删除尾随空格。查看this@vikscool这不是带分隔符的文件。这是一个固定宽度的文件。将整行拆分为一个空格行。拆分(“”).Trim()
。我假设唯一可能包含空格作为值(而不是分隔符)的字段是名称。因此,您可能希望得到第一个和最后4个索引的拆分字符串,中间的任何剩余索引都是字段名的值。
ID = 1
Score = 11
Ping = 45
Guid = 176387877
Name = Player 1
Last Msg = 3250
Port = 3647
Rate = 25000
ID = 2
Score = 23
Ping = 61
Guid = 425716719
Name = Player 2
Last Msg = 3250
Port = 5978
Rate = 25000