为什么regex不能正常工作?
string findarg2 = ",\\s(.*?),\\s";
foreach (Match getarg2 in Regex.Matches(tmptwopart, findarg2))
if (getarg2.Success)
{
for (int m = 1; m < getarg2.Groups.Count; m++)
{
int n;
bool needpointer = false;
for (n = getarg2.Groups[m].Value.Length - 1; n > -1; n--)
{
if (getarg2.Groups[m].Value[n] == ' ')
break;
else if (getarg2.Groups[m].Value[n] == '*')
{
needpointer = true;
break;
}
}
n++;
string part1 = getarg2.Groups[m].Value.Remove(n);
string part2 = getarg2.Groups[m].Value.Remove(0, n);
Console.WriteLine(getarg2.Groups[m] + " =->" +part1+ " AND " + part2);
Console.ReadKey();
if (needpointer)
{
createarglist.Append("<< *(" + part1 + ")" + part2);
}
else
{
createarglist.Append("<< " + part2);
}
createarglistclear.Append(part2+",");
} }输入字符串示例:
(DWORD code, bool check, float *x1, float *y1, float *x2, float *y2)输出:
<< check<< *(float *)y1预期:
<< check<< *(float *)x1<< *(float *)y1<< *(float *)x2发布于 2013-11-14 15:48:29
表达式不起作用的原因是它“消耗”了逗号:匹配check的部分也会在逗号之后耗尽逗号,从而阻止float *x1被匹配;匹配float *y1的表达式也是如此。
将表达式更改为使用lookaheads和lookaheads应该有效。但是,这可能还不够,因为第一次匹配的前面不会有逗号,最后一次匹配之后也不会有逗号。
在这种情况下使用的一个更好的表达式应该是:
(?<=[(,])\\s*([^,)]*)\\s*(?=[,)])下面是一个完整的代码示例:
foreach (Match m in Regex.Matches(
"(DWORD code, bool check, float *x1, float *y1, float *x2, float *y2)"
, "(?<=[(,])\\s*([^,)]*)\\s*(?=[,)])")
) {
for (var i = 1 ; i != m.Groups.Count ; i++) {
Console.WriteLine("'{0}'", m.Groups[i]);
}
}下面是一个关于理想的演示,它按照预期产生了六个组:
'DWORD code'
'bool check'
'float *x1'
'float *y1'
'float *x2'
'float *y2'发布于 2013-11-14 15:47:49
这是因为你在使用后面的逗号。也就是说,您已经匹配了后面的逗号,因此它不匹配为您要匹配的下一个实体的前导逗号。使用零宽度断言代替:
string findarg2 = "(?<=,\\s)(.*?)(?=,\\s)";这些断言分别被称为“查找”和“前瞻性”断言。
发布于 2013-11-14 16:04:27
这可以一蹴而就:
string input = "(DWORD code, bool check, float *x1, float *y1, float *x2, float *y2)";
string pattern = @"(?:\([^,]*,\s*[^\s,]*\s+([^,]+)|\G),\s+(\S+)\s*( \*)?((?>[^*,)]+))(?>(?=,[^,]+,)|.*)";
string replacement = "$1<< *($2$3)$4";
Regex rgx = new Regex(pattern);
string result = "<<" + rgx.Replace(input, replacement);https://stackoverflow.com/questions/19981924
复制相似问题