I have the following regex Pattern.compile("^" + prefix + "[a-zA-Z]")
, where it'll match the prefix in the beginning of a word, it works fine for !
for example, but when I try using ?
it breaks, as an attempt to escape it I tried turning it into Pattern.compile("^\\" + prefix + "[a-zA-Z]")
but I get the error Illegal/unsupported escape sequence
, doing \\\\
seemed to make it handle the ?
correctly but then the !
stopped working.
I'm kinda lost on how I would prevent the String from affecting the pattern itself.
Asked
Active
Viewed 19 times
0

User12322341232142
- 93
- 1
- 8
-
Use `"\\?"` to escape it. There are 2 backslashes because it's also in a Java string. – user May 19 '20 at 20:56
-
2Does this answer your question? [How to escape text for regular expression in Java](https://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java). E.g. `Pattern.compile("^" + Pattern.quote(prefix) + "[a-zA-Z]")` – that other guy May 19 '20 at 20:57
-
How about `Pattern.compile(prefix.startsWith("?") ? "^\\\\" : "^" + prefix + "[a-zA-Z]")` – Arvind Kumar Avinash May 19 '20 at 21:18