您好我想搜索特定字符串的第一个匹配项,并捕获一组数字和更改字符之间的值。
使用Nate Barbettini的https://dotnetfiddle.net/vhkUV5示例我将其剔除进行我几乎需要做的事情,它不会编译,而且从我看到的我的RegEx离开之后所以我非常需要帮助。
在我的例子中,我想找到chrome.exe的第一次出现PID值“116c”而不是所有三个PID值。获得一个PID值的最佳方法是什么?
代码:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var output = @"
0a80 6e 6f 74 65 70 61 64 2b 2b 2e 65 78 65 20 20 20 notepad++.exe
0a90 50 49 44 3d 31 64 38 63 7c 30 37 35 36 34 0d 0a PID=1d8c|07564..
0aa0 6a 68 69 5f 73 65 72 76 69 63 65 2e 65 78 20 20 jhi_service.ex
0ab0 50 49 44 3d 31 38 64 34 7c 30 36 33 35 36 0d 0a PID=18d4|06356..
0ac0 4c 4d 53 2e 65 78 65 20 20 20 20 20 20 20 20 20 LMS.exe
0ad0 50 49 44 3d 31 63 36 38 7c 30 37 32 37 32 0d 0a PID=1c68|07272..
0ae0 63 6d 64 2e 65 78 65 20 20 20 20 20 20 20 20 20 cmd.exe
0af0 50 49 44 3d 30 66 37 38 7c 30 33 39 36 30 0d 0a PID=0f78|03960..
0b00 63 6f 6e 68 6f 73 74 2e 65 78 65 20 20 20 20 20 conhost.exe
0b10 50 49 44 3d 30 62 64 30 7c 30 33 30 32 34 0d 0a PID=0bd0|03024..
0b20 76 63 74 69 70 2e 65 78 65 20 20 20 20 20 20 20 vctip.exe
0b30 50 49 44 3d 31 38 30 38 7c 30 36 31 35 32 0d 0a PID=1808|06152..
0b40 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b50 50 49 44 3d 31 31 36 63 7c 30 34 34 36 30 0d 0a PID=116c|04460..
0b60 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b70 50 49 44 3d 31 36 39 34 7c 30 35 37 38 30 0d 0a PID=1694|05780..
0b80 63 68 72 6f 6d 65 2e 65 78 65 20 20 20 20 20 20 chrome.exe
0b90 50 49 44 3d 31 30 62 30 7c 30 34 32 37 32 0d 0a PID=10b0|04272..";
var regex = new Regex(@"chrome.exe[\s].................................................................(.*)........");
var resultList = new List<string>();
foreach (Match match in regex.Matches(output))
{
resultList.Add(match.Groups[1].ToString());
}
var pid = string.Join(", ", resultList);
Console.WriteLine(pid);
}
}
输出:
116c, 1694, 10b0
我非常新,所以欢迎任何帮助或指示。
答案 0 :(得分:0)
试试这段代码:
var regex = new Regex("chrome\\.exe\\s*.*PID=(.*)\\|");
var pid = regex.Matches(output)
.Cast<Match>()
.Select(match => match.Groups[1].ToString())
.First();
您可以测试正则表达式here。