Regex 上下文正则表达式

Regex 上下文正则表达式,regex,Regex,我有一个逗号分隔的单词列表,我想从中删除逗号并替换为空格: elements-(a,b,c,d) 变成: elements-(a b c d) 问题是,当且仅当该列表在特定上下文中(例如,仅以元素-()为前缀)时,如何使用正则表达式执行此操作: 以下是: static string Replace(string text) { return Regex.Replace( text, @"(?<=elemen

我有一个逗号分隔的单词列表,我想从中删除逗号并替换为空格:

elements-(a,b,c,d)
变成:

elements-(a b c d)
问题是,当且仅当该列表在特定上下文中(例如,仅以元素-()为前缀)时,如何使用正则表达式执行此操作:

以下是:

    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-\((\w+,)*)(\w+),(?=(\w+,)*\w+\))",
            "$2 "
        );
    }
    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-)\(((\w+,)+\w+)\)",
            m => string.Format("({0})", m.Groups[1].Value.Replace(',', ' '))
        );
    }
有许多元素-(a、b、c、d)和许多其他元素-(e、f、g、h)

应成为:

There are a number of elements-(a b c d) and a number of other elements-(e f g h)

使用正则表达式执行此操作的正确方法是什么?

对于上下文正则表达式,可以使用。环顾断言用于断言某些内容必须为真才能成功匹配,但它们不使用任何字符(因此为“零宽度”)

在您的案例中,您希望使用积极的向后看和向前看断言。在C#中,您可以执行以下操作:

    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-\((\w+,)*)(\w+),(?=(\w+,)*\w+\))",
            "$2 "
        );
    }
    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-)\(((\w+,)+\w+)\)",
            m => string.Format("({0})", m.Groups[1].Value.Replace(',', ' '))
        );
    }
积极前瞻断言的基本方法仍然是一样的

示例输出:

“(x,y,z)元素-(a,b)(m,m,m)元素-(c,d,e,f,g,h)

…变成


“(x,y,z)元素-(a b)(m,m,m)元素-(c d e f g h)”

对于上下文正则表达式,可以使用。环顾断言用于断言某些内容必须为真才能成功匹配,但它们不使用任何字符(因此为“零宽度”)

在您的案例中,您希望使用积极的向后看和向前看断言。在C#中,您可以执行以下操作:

    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-\((\w+,)*)(\w+),(?=(\w+,)*\w+\))",
            "$2 "
        );
    }
    static string Replace(string text)
    {
        return Regex.Replace(
            text,
            @"(?<=elements\-)\(((\w+,)+\w+)\)",
            m => string.Format("({0})", m.Groups[1].Value.Replace(',', ' '))
        );
    }
积极前瞻断言的基本方法仍然是一样的

示例输出:

“(x,y,z)元素-(a,b)(m,m,m)元素-(c,d,e,f,g,h)

…变成


“(x,y,z)元素-(a b)(m,m,m)元素-(c d e f g h)”

有人回答了你的问题,所以你应该确定他们的答案为接受。有人回答了你的问题,所以你应该确定他们的答案为接受。