c# - 正则表达式 ",\\s(.*?),\\s"

标签 c# 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

最佳答案

这是因为您正在使用尾随逗号。也就是说,您已经匹配了尾随逗号,因此它不会作为您尝试匹配的下一个实体的前导逗号进行匹配。改用零宽度断言:

string findarg2 = "(?<=,\\s)(.*?)(?=,\\s)";

这些分别称为“后视”和“先行”断言。

关于c# - 正则表达式 ",\\s(.*?),\\s",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981924/

相关文章:

c# - 如果存在于 XmlNodeList C# 中的 XML 节点上

c# - 是否可以用 C#(而不是 c\c++)编写 DirectShow 过滤器?

python - 使用正则表达式匹配数据框中的字符串并替换 - python

java - 在 Web 收获 xml 中使用正则表达式

regex - 在以 "/"分隔的字符串中查找重复的单词

c# - 仅当项目中存在属性时才在 aspx 中使用 Eval - 抛出 DataBinding 异常

c# - 无法在运行时访问 SuppressMessage 属性

c# - 在 List<> 中查找包含值的元素

css - RegExp 搜索并替换 css 中图像的路径

php - 使用 preg_replace 时如何增加替换字符串中的计数?