java - StringIndexOutOfBoundsException on replaceAll using lookahead and backslash? -
i'd escape quotes (single , double) , backslashes of string.
i'm trying single call of mystring.replaceall. regex match , replace (?=['\"\\\\])
(escaped java syntax), or more readable: (?=['!\])
(unescaped syntax). i'm doing lookahead, because want keep quotes , backslashes, , insert escape character before each of them.
if use +
escape character, works charm (all strings below in escaped java syntax):
"abc'def\"ghi\\jkl".replaceall("(?=['\"\\\\])", "+")
results in "abc+'def+\"ghi+\\jkl"
. yay!
however, if use backslash escape character, i'm getting stringindexoutofboundsexception instead: string index out of range: 1
.
the call looks this: "abc'def\"ghi\\jkl".replaceall("(?=['\"\\\\])", "\\\\")
that's odd... inserted backslash interfere somehow backslash within lookahead regex? if so, how can avoid behavior?
here full testing code:
import static org.junit.assert.assertequals; import static org.junit.assert.assertfalse; import static org.junit.assert.asserttrue; import org.junit.test; public class regextest { @test public void test() { assertequals("abc\\'def\\\"ghi\\\\jkl", "abc'def\"ghi\\jkl".replaceall("(?=['\"\\\\])", "\\\\")); } }
any appreciated!
Comments
Post a Comment