为什么正则表达式不能正常工作?
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
最佳答案
这是因为您正在使用尾随逗号。也就是说,您已经匹配了尾随逗号,因此它不会作为您尝试匹配的下一个实体的前导逗号进行匹配。改用零宽度断言:
string findarg2 = "(?<=,\\s)(.*?)(?=,\\s)";
这些分别称为“后视”和“先行”断言。
关于c# - 正则表达式 ",\\s(.*?),\\s",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981924/