当涉及到regex时,我是一个完全的新手,我希望帮助在以下内容中匹配一个表达式:
{ValidFunctionName}({parameter}:"{value}")
{ValidFunctionName}({parameter}:"{value}",
{parameter}:"{value}")
{ValidFunctionName}()其中{x}是我想要匹配的参数,{$%}可以是任何值“$例如,{value}必须用引号括起来。
ThisIsValid_01(a:"40")将是"ThisIsValid_01","a","40“
ThisIsValid_01(a:"40", b:"ZOO")可以是"ThisIsValid_01","a","40","b","ZOO“
01_ThisIsntValid(a:"40")不会退回任何东西
ThisIsntValid_02(a:40)不会返回任何内容,因为40没有用引号括起来。
ThisIsValid_02()将返回"ThisIsValid_02“
对于一个有效的函数名,我遇到了:"A-Za-z_*“,但我无论如何也想不出如何匹配其余的函数名。我一直在http://regexpal.com/上尝试让有效的匹配符合所有条件,但是没有用:(
如果你也友好地解释正则表达式,那就更好了,这样我就可以学习了:)
发布于 2010-09-08 06:57:50
其他人已经给出了一个简单的字符串列表,但是考虑到强类型和适当的类结构,我将提供一个正确封装数据的解决方案。
首先,声明两个类:
public class ParamValue // For a parameter and its value
{
public string Parameter;
public string Value;
}
public class FunctionInfo // For a whole function with all its parameters
{
public string FunctionName;
public List<ParamValue> Values;
}然后执行匹配并填充FunctionInfo列表:
(顺便说一句,我对正则表达式做了一些小的修正...它现在将正确匹配标识符,并且不会将双引号作为每个参数的“value”的一部分。)
Regex r = new Regex(@"(?<function>[\p{L}_]\w*?)\((?<inner>.*?)\)");
Regex inner = new Regex(@",?(?<param>.+?):""(?<value>[^""]*?)""");
string input = "_test0(a:\"lolololol\",b:\"2\") _test1(ghgasghe:\"asjkdgh\")";
var matches = new List<FunctionInfo>();
if (r.IsMatch(input))
{
MatchCollection mc = r.Matches(input);
foreach (Match match in mc)
{
var l = new List<ParamValue>();
foreach (Match m in inner.Matches(match.Groups["inner"].Value))
l.Add(new ParamValue
{
Parameter = m.Groups["param"].Value,
Value = m.Groups["value"].Value
});
matches.Add(new FunctionInfo
{
FunctionName = match.Groups["function"].Value,
Values = l
});
}
}然后,您可以使用像FunctionName这样的标识符很好地访问该集合
foreach (var match in matches)
{
Console.WriteLine("{0}({1})", match.FunctionName,
string.Join(", ", match.Values.Select(val =>
string.Format("{0}: \"{1}\"", val.Parameter, val.Value))));
}https://stackoverflow.com/questions/3662722
复制相似问题