Results 1 to 2 of 2

Thread: [2.0] [resolved] Regex String Replacement Question

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Resolved [2.0] [resolved] Regex String Replacement Question

    I have a string that I'm using a Regular Expression to look for matches. The problem I have is if there are duplicate matches returned in Regex.Matches(...) and I loop through each match to do a String.Replace to format the matches, they will be replaced duplicate times, at least as many times as there are duplicates found.

    Example:
    Code:
    string str = "ab9    a  b123	  ab4		ab2";
    
    foreach (Match m in Regex.Matches(str, "a[ \t]*b(?=[0-9]+)"))
    {
    	//MessageBox.Show(m.Value);
    	str = str.Replace(m.Value, "<tag>" + m.Value + "</tag>");
    }
    The code is looking for 'a' followed by zero or more spaces or tabs, followed by 'b' and looks behind, but doesn't include in the match, one or more numbers.

    So the matches come back as "ab", "a b", "ab", and "ab" and I want to wrap each match with <tag></tag>

    What I want is for the result string to look like:
    Code:
    "<tag>ab</tag>9    <tag>a  b</tag>123	  <tag>ab</tag>4		<tag>ab</tag>2"
    but the duplicate matches cause each "ab" to be replaced multiple times so the result is:
    Code:
    <tag><tag><tag>ab</tag></tag></tag>9    <tag>a  b</tag>123	  
    <tag><tag><tag>ab</tag></tag></tag>4		<tag><tag><tag>ab</tag></tag></tag>2

    Is there any way around this other than storing the matches in a unique list and looping through the unique list instead of the Matches list?
    Last edited by wey97; Dec 11th, 2006 at 05:35 PM.

  2. #2
    Addicted Member
    Join Date
    Jan 2000
    Location
    BC, Canada
    Posts
    142

    Re: [2.0] Regex String Replacement Question

    try this:

    Code:
    public void  ReplaceProcess()
        {
            string str = "ab9    a  b123	  ab4		ab2";
            string sR = "a[ \t]*b(?=[0-9]+)";
            Regex r = new Regex(sR);
            MatchEvaluator myEvaluator = new MatchEvaluator(ReplaceMe);
            str = r.Replace(str, myEvaluator );
            MessageBox.Show(str);
    
            }
    
            public string ReplaceMe(Match m)
             {
                
                return "<tag>" +m+"</tag>";
            }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width