正则表达式帮助 - 再次忽略括号,ands,ors和whitespace

时间:2014-03-31 13:54:50

标签: c# .net regex

考虑以下英语短语

FRIEND AND COLLEAGUE AND (FRIEND OR COLLEAGUE AND (COLLEAGUE AND FRIEND AND FRIEND))

我希望能够以编程方式将任意短语(如上所述)更改为:

SELECT * FROM RelationTable R1 JOIN RelationTable R2 ON R2.RelationName etc etc WHERE 
R2.RelationName = FRIEND AND R2.RelationName = Colleague AND (R3.RelationName = FRIENd, 
etc. etc.

我的问题是。如何获取初始字符串,删除以下单词和符号:AND,OR,(,), 然后更改每个单词,并创建一个新字符串。

我可以做大部分,但我的主要问题是,如果我做一个string.split并且只得到我关心的词,我就不能在原始字符串中真正替换它们,因为我缺少原始索引。让我用一个较小的例子来解释:

string input = "A AND (B AND C)"
Split the string for space, parenthesies, etc, gives: A,B,C
input.Replace("A", "MyRandomPhrase")

但在AND中有一个A. 所以我开始尝试创建一个匹配精确单词,后分割和替换的正则表达式。它开始看起来像这样:

"(\(|\s|\))*" + itemOfInterest + "(\(|\s|\))+"

我是在正确的轨道还是我过于复杂的事情......谢谢!

2 个答案:

答案 0 :(得分:2)

您可以尝试使用Regex.Replace\b字边界正则表达式

string input = "A AND B AND (A OR B AND (B AND A AND A))";
string pattern = "\\bA\\b";
string replacement = "MyRandomPhrase";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

答案 1 :(得分:-1)

class Program
{
    static void Main(string[] args)
    {

        string text = "A AND (B AND C)";

        List<object> result = ParseBlock(text);

        Console.ReadLine();
    }

    private static List<object> ParseBlock(string text)
    {
        List<object> result = new List<object>();

        int bracketsCount = 0;
        int lastIndex = 0;

        for (int i = 0; i < text.Length; i++)
        {
            char c = text[i];

            if (c == '(')
                bracketsCount++;
            else if (c == ')')
                bracketsCount--;

            if (bracketsCount == 0)
                if (c == ' ' || i == text.Length - 1)
                {
                    string substring = text.Substring(lastIndex, i + 1 - lastIndex).Trim();

                    object itm = substring;

                    if (substring[0] == '(')
                        itm = ParseBlock(substring.Substring(1, substring.Length - 2));

                    result.Add(itm);

                    lastIndex = i;
                }
        }
        return result;
    }
}