Regular Expressions Pattern

AlexG2207

New member
Joined
Sep 29, 2015
Messages
1
Programming Experience
5-10
Hello,

I'm trying to take a long URL string and make a change to part of it using Regular Expressions.

Here is an example of part of the string to change:

"property+address%22%0a&start=100&rows=200&fl=doc_id%2c+doc_cmt_description&wt=csv&indent=true>"

I need to be able to change the following parts of the string:
start=100 AND rows=200

I just need to be able to change the numbers. It is unknown how many digits would in these so I figured regular expressions would be the best, but the pattern part to change it is tough. With what I have, it removes the start= and rows=, but does not fill them in at the correct spot in the string.


C#:
int startRows = 0;
int getRows = 500;
string firstReplacement = "start=" + startRows;
string secondReplacement = "rows=" + getRows;
string firstPattern = "start=.*&";
string secondPattern = "rows=.*&";
Output = Regex.Replace(Input, firstPattern, firstReplacement, RegexOptions.IgnoreCase);
Output = Regex.Replace(Input, secondPattern, secondReplacement, RegexOptions.IgnoreCase);
 

wim sturkenboom

Well-known member
Joined
Aug 6, 2014
Messages
85
Location
Roodepoort, South Africa
Programming Experience
10+
Regular expressions are greedy by default and will try to match as much as possible; it will therefore 'find' up to the last '&' in your input. The first replace in your code will therefore replace the following part of the string

C#:
start=100&rows=200&fl=doc_ id%2c+doc_cmt_description&wt=csv&

You can force the regular expression engine to be lazy (non-greedy) by adding a question mark after the quantifier ('*'). You also have a design flaw because you do two replacements, each time on the input string. The first one should be on the input string, the second one on the result of the previous replace (Output).

        static void Main(string[] args)
        {
            string Input = "property+address%22%0a&start=100&rows=200&fl=doc_ id%2c+doc_cmt_description&wt=csv&indent=true";
            string Output = "";

            int startRows = 0;
            int getRows = 500;
            string firstReplacement = "start=" + startRows;
            string secondReplacement = "rows=" + getRows;
            string firstPattern = "start=.*?&";
            string secondPattern = "rows=.*?&";
            Output = Regex.Replace(Input, firstPattern, firstReplacement, RegexOptions.IgnoreCase);
            Console.WriteLine(Output);
            Output = Regex.Replace(Output, secondPattern, secondReplacement, RegexOptions.IgnoreCase);
            Console.WriteLine(Output);
            Console.ReadLine();
        }
 
Last edited:
Top Bottom