Java - Is it possible to store metacharacters like dot in a character variable?

202 views Asked by At

Metacharacters like ., \, {, ^, |, ] can be escaped with the \ character. But char variables can only store exactly one character. So is it possible to store these special characters in char variables in Java?

Maybe you only need to use the escape character in String variables?

3

There are 3 answers

0
RaminS On BEST ANSWER

Yes, it is possible.

char c = '.'; 

Escaping meta-characters is only when you're dealing with Strings, not chars.

0
Rory Malcolm On

it's perfectly possible to store these characters in char variables. Are you using "" quotes instead of ''? It's a common error with char.

0
Tech-ish On

All of the characters in your question can be stored in either a String or a char variable without escaping them except for the escape character \ itself. You only have to escape them if some method that is acting on the string or char may behave differently if it can have a mix of normal characters and those which have special meaning.

String.format() is a good example of where it is likely you might have both. If you want to store the escape char \ in a single character you can do something like this:

char c = '\\'