简体   繁体   中英

Regular Expression for string replace

I have input string as below

("abc xyz" OR "def") AND (ghi OR jkl) AND ("mno poe" OR stu)

i want it to replace with

(myfun("abc xyz") OR myfun("def")) AND (myfun(ghi) OR myfun(jkl)) AND (myfun("mno poe") OR myfun(stu))

i want that string with in double quotation mark or single word get replace with myfun(<string matched>)

can any body help me , how can i set this using regular expression ? Thanks Meghana

The following C# quoted expression matches quoted strings and words that are not AND or OR :

@"(""(?:[^\\""]+|\\.)*""|\b(?!(?:AND|OR)\b)\w+\b)"

Replace it with:

"myfun($1)"

If all upper case words are operators, you can use this expression instead:

@"(""(?:[^\\""]+|\\.)*""|\b(?![A-Z]+\b)\w+\b)"

Updated to meet OPs new requirements the expression would look like:

@"(?i)(""(?:[^\\""]+|\\.)*""|\b(?!(?:and|or|not|near)\b)\w+\b)"

Added (?i) to make it case insensitive and completed the list of operator tokens.

Replace

(".+?"|\b\w+?\b)(?<!(OR|AND)) 

with

myfun($1)
    [Test]
    public void Test2()
    {
        string input = "(\"abc xyz\" OR \"def\") AND (ghi OR jkl) AND (\"mno poe\" OR stu)";
        string expected = "(myfun(\"abc xyz\") OR myfun(\"def\")) AND (myfun(ghi) OR myfun(jkl)) AND (myfun(\"mno poe\") OR myfun(stu))";
        string actual = Regex.Replace(input, @"([\""\']).*?(\1)|\b(?!AND|OR)\w+\b", ReplaceWord);
        Assert.AreEqual(expected, actual);
    }

    private static string ReplaceWord(Match m)
    {
        return string.Format("myfun({0})", m.Value);
    }
List<string> reservedWords = new List<string>() { "AND","OR","NEAR","NOT" };
var rep = Regex.Replace(
            inputString,
            @"([\""][\w ]+[\""])|(\w+)",
            m=> reservedWords.Contains(m.Value) ? m.Value : "myfun(" + m.Value + ")" 
          );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM