您可以使用这种模式,它允许一次性使用单独的参数捕获所有功能:
(?<funcName>\w+)\(IN: ?|OUT: ?|\G(?<inParam>[^,;()]+)?(?=[^)(;]*;)\s*[,;]\s*|\G(?<outParam>[^,()]+)(?=[^;]*\s*\))\s*[,)]\s*
图案细节:
(?<funcName>\w+)\(IN: ? # capture the function name and match "(IN: "
| # OR
OUT: ? # match "OUT: "
| # OR
\G(?<inParam>[^,;()]+)? # contiguous match, that captures a IN param
(?=[^)(;]*;) # check that it is always followed by ";"
\s*[,;]\s* # match "," or ";" (to be always contiguous)
| # OR
\G(?<outParam>[^,()]+)? # contiguous match, that captures a OUT param
(?=[^;]*\s*\)) # check that it is always followed by ")"
\s*[,)]\s* # match "," (to be always contiguous) or ")"
(要获得更清晰的结果,您必须走到匹配数组(使用 foreach)并删除空条目)
示例代码:
static void Main(string[] args)
{
string subject = @"Add_func(IN: port_0, in_port_1; OUT: out_port99)
Some_func(IN:;OUT: abc_P1)
shift_data(IN:po1_p0;OUT: po1_p1, po1_p2)
Some_func2(IN: input_portA;OUT:)";
string pattern = @"(?<funcName>\w+)\(IN: ?|OUT: ?|\G(?<inParam>[^,;()]+)?(?=[^)(;]*;)\s*[,;]\s*|\G(?<outParam>[^,()]+)(?=[^;]*\s*\))\s*[,)]\s*";
Match m = Regex.Match(subject, pattern);
while (m.Success)
{
if (m.Groups["funcName"].ToString() != "")
{
Console.WriteLine("\nfunction name: " + m.Groups["funcName"]);
}
if (m.Groups["inParam"].ToString() != "")
{
Console.WriteLine("IN param: " + m.Groups["inParam"]);
}
if (m.Groups["outParam"].ToString() != "")
{
Console.WriteLine("OUT param: "+m.Groups["outParam"]);
}
m = m.NextMatch();
}
}
另一种方法是匹配一个字符串中的所有 IN 参数和所有 OUT 参数,然后将这些字符串拆分为\s*,\s*
例子:
string pattern = @"(?<funcName>\w+)\(\s*IN:\s*(?<inParams>[^;]*?)\s*;\s*OUT\s*:\s*(?<outParams>[^)]*?)\s*\)";
Match m = Regex.Match(subject, pattern);
while (m.Success)
{
string functionName = m.Groups["function name"].ToString();
string[] inParams = Regex.Split(m.Groups["inParams"].ToString(), @"\s*,\s*");
string[] outParams = Regex.Split(m.Groups["outParams"].ToString(), @"\s*,\s*");
// Why not construct a "function" object to store all these values
m = m.NextMatch();
}