.net - Escaping mid-string percent signs, is a regex the best option? -
i need escape %
characters in string entered user - replacing them [%]
unless @ start or end of string.
for example %foo%foo[%]foo%
should become %foo[%]foo[%]foo%
. whitespace isn't concern: escaping mid-string percent signs.
a regular expression of [^[]%[^\]]
match mid-string percentages, adjacent characters (so o%f
in example).
is there reasonable regular expression match mid-string non-escaped percentage characters?
i wondering if non-regex solution preferable, such as
iterating through characters in string, , building replacement string percentages escaped
const string test = "%foo%foo[%]foo%"; stringbuilder escaped = new stringbuilder(); escaped.append(test[0]); (int = 1; < test.length - 1; i++) { if (test[i] != '%' || (test[i - 1] == '[' && test[i] == '%' && test[i + 1] == ']')) { escaped.append(test[i]); } else { escaped.append("[%]"); } } escaped.append(test[test.length - 1]);
-or-
doing three-pass token-based replacement such as
const string token = "!percent!"; // string hope(!) never encounter in string we're escaping const string test = "%foo%foo[%]foo%"; string escaped = test.replace("[%]", token); escaped = replaced.replace("%", token); escaped = replaced.replace(token, "[%]");
(although escape first or last character percentages, isn't want)
as why need - escaping like
filter expression values entered user being applied datatable
.
you might try:
(?<!^)((?<!\[)|(?!.\]))%(?!$)
it's bit ugly because wanted match cases foo[%foo , foo%]foo.
(?<!^) - prevents match @ start of string (negative behind) (?!$) - prevents match @ end of string (negative ahead) (?<!\[)|(?!.\]) - prevents match if previous '[' , ']' next.
you use regex command like:
regex.replace(input, @"(?<!^)((?<!\[)|(?!.\]))%(?!$)", x => "[" + x + "]")
Comments
Post a Comment