Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Match %foo% but not %%foo%%

Last post 07-27-2010, 7:30 PM by Aussie Susan. 3 replies.
Sort Posts: Previous Next
  •  07-26-2010, 1:35 PM 70116

    Match %foo% but not %%foo%%

    Working in C#/.NET

    I'm trying to do string replacement. Our previous string replacement matched %anything%. Due to issues with having 2 % in the same string I'm trying to allow users to enter a % as %% and not have it identified for string replacement.

     

    These should each find a single%foo% match:

    "foo%foo%foo"
    "%foo%foo"
    "foo%foo%"
    "%foo%"

     

    These should have no matches:

    "foo"
    "%%"
    "%%foo"
    "foo%%"
    "%%foo%%"
    "foo%%foo%%foo"
    "foo%%foo%%"
    "%%foo%%foo"
    "%foo%%"
    "%foo%%foo"
    "foo%foo%%"
    "foo%foo%%foo"
    "%%foo%"
    "%%foo%foo"
    "foo%%foo%"
    "foo%%foo%foo"

     

    Have tried variations on [^%]?%[^%]+%[^%] with no luck.

    Thanks!

  •  07-26-2010, 7:14 PM 70142 in reply to 70116

    Re: Match %foo% but not %%foo%%

    Try:

    (?<!%)%\w+%(?!%)

    Feel free to change the '\w' in the middle to whatever is the correct operator(s) in your situation.

    This uses lookbehind and lookaheads to make sure that there is no second "%" before or after the main search phrase. This also has the advantage of only making the entire match (which is what is deleted and replaced by the replacement string) only the characters you are interested in - your pattern would include the non-"%" characters before and after which you would need to take into account in the replacement string.

    Susan

  •  07-27-2010, 1:24 PM 70157 in reply to 70142

    Re: Match %foo% but not %%foo%%

    That worked perfectly, thanks!

    I changed the \w to [^%] since we allow spaces, punctuation, etc between tags.

     

    I'll have to read up on look-ahead and look-behind since this is the first I've heard of them as far as regex

  •  07-27-2010, 7:30 PM 70160 in reply to 70157

    Re: Match %foo% but not %%foo%%

    Just remember that '[^%]' will match anything that is not a "%", including newline characters etc.. Therefore it will match everything between the 2 "%" characters in:

    I scored 20% in my exam
    wombats
    can't fly 100% as they fall rather fast

    You may want to be a little more restrictive either in what can be between the "%" characters or the context within which the "%" delimited item occurs.

    Susan

View as RSS news feed in XML