更新时间:2022-06-03 22:02:34
通常情况下,你需要两个步骤获得的所有数据。
首先,匹配/验证整个功能:
Generally, you'd need two steps to get all data.
First, match/validate the whole function:
function\((?<parameters>((\/\*[a-zA-Z]+\*\/)?[0-9a-zA-Z_$]+,?)*)\)
请注意,现在你有一个参数
组所有参数。你可以搭配一些样式再次得到所有的参数匹配,或在这种情况下,拆分对,
。
Note that now you have a parameters
group with all parameters. You can match some of the pattern again to get all matches of parameters, or in this case, split on ,
.
如果你使用的.Net,不管怎样,你很幸运。净保留每个组的所有捕获的全部记录,这样你就可以使用集合:
If you're using .Net, by any chance, you're in luck. .Net keeps full record of all captures of each group, so you can use the collection:
match.Groups["param"].Captures
一些注意事项:
Some notes:
/
有没有什么特别的意义有(C#/。网络不具有正则表达式的分隔符)(?<type>(\/\*[a-zA-Z]+\*\/)?)
/
has no special meaning there (C#/.Net doesn't have regex delimiters).下面是一个使用捕获的一个例子。此外,主要的一点是保持在关系类型
和参数
:要捕捉空的类型,所以你不'T失去计数。
图案:
Here's an example of using the captures. Again, the main point is maintaining the relation between type
and param
: you want to capture empty types, so you don't lose count.
Pattern:
function
\(
(?:
(?:
/\*(?<type>[a-zA-Z]+)\*/ # type within /* */
| # or
(?<type>) # capture an empty type.
)
(?<param>
[0-9a-zA-Z_$]+
)
(?:,|(?=\s*\))) # mandatory comma, unless before the last ')'
)*
\)
code:
Code:
Match match = Regex.Match(s, pattern, RegexOptions.IgnorePatternWhitespace);
CaptureCollection types = match.Groups["type"].Captures;
CaptureCollection parameters = match.Groups["param"].Captures;
for (int i = 0; i < parameters.Count; i++)
{
string parameter = parameters[i].Value;
string type = types[i].Value;
if (String.IsNullOrEmpty(type))
type = "NO TYPE";
Console.WriteLine("Parameter: {0}, Type: {1}", parameter, type);
}