Click here to Skip to main content
15,889,838 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have string like this "Code = ? And Desc = ? Or Qty = ?". I would like to
replce with regex to this "Code = @0 AND Desc = @1 OR Qty = @2".

"?" can be more and AND OR shoul be Capitalize

how can i do this. thanks
Posted
Updated 30-Dec-14 10:07am
v3
Comments
Zoltán Zörgő 30-Dec-14 16:24pm    
Replacing is only a side-feaure of regexp tools. But the exact method depends on the language/regexp tool you use. Please specify. And please expalain the bold sentance, since it makes no sense, but looks important to you. And better give a more concrete example.
Maciej Los 30-Dec-14 17:37pm    
You can't! As Zoltan mentioned, regex is not for such of functionality.
Andreas Gieriet 30-Dec-14 17:43pm    
Regex can't count. I.e. if you want a regex that replaces the first ? with @0, the second with @1, etc. than you must use other means. Either a hard-coded regex (explicitly program all possible replacements) - or better: use some other means, e.g. a loop combined with regex.
Cheers
Andi

1 solution

You have not given any flavor of regex, so I chose my own (C#) in this solution.

A possible approach is to replace tokens in multiple loops. The C# regex allows to globally replace patterns (this covers the and/or tokens). To overcome the limit that regex cannot count, you may apply lambda expressions that count up a variable that is defined outside of that lambda expression.

E.g. a crude version of this could be coded in C# like this:
C#
static string Translate(string input)
{
    string result = input;
    result = Regex.Replace(result, @"\b(and|or)\b",
                           m => m.Groups[1].Value.ToUpper(),
                           RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);
    int i = 0;
    result = Regex.Replace(result, @"(\?)", m => "@" + (i++).ToString());
    return result;
}

static void Main(string[] args)
{
    string input = "Code = ? And Desc = ? Or Qty = ?";
    Console.WriteLine("{0} --> {1}", input, Translate(input));
}
You may of course try to merge all into one regex but that becomes quite messy.
Cheers
Andi
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900