我正在解析我的/etc/passwd文件,看起来像这样:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
Run Code Online (Sandbox Code Playgroud)
我希望我的程序返回以下内容:
root
bin
daemon
...
sync
Run Code Online (Sandbox Code Playgroud)
我目前的代码是这样的:
Regex expression = new Regex(@"^\w*");
foreach (Match myMatch in expression.Matches(txt))
{
txtout.Text = myMatch.ToString();
}
Run Code Online (Sandbox Code Playgroud)
但是,我只是回来root了这段代码.我怎样才能退回每一行?
使用正则表达式是一种矫枉过正,如果我理解你的意图正确,你想在第一个':'字符之前检索子字符串.
using (StreamReader reader = new StreamReader ("/etc/passwd")) {
string line = "";
while((line = reader.ReadLine()) != null) {
string userName = line.Substring(0, line.IndexOf(':'));
}
}
Run Code Online (Sandbox Code Playgroud)