Ammad
Ammad

Reputation: 4235

Java escaping hyphen "-" character using regex

I am using Java and have string which have value as shown below,

String data = "vale-cx";
data = data.replaceAll("\\-", "\\-\\");

I am replacing "-" inside of it and it is not working. Final value i am looking is "vale\-cx". Meaning, hyphen needs to be escaped.

Upvotes: 1

Views: 6667

Answers (3)

shmosel
shmosel

Reputation: 50766

Hyphen doesn't need to be escaped, but backslash needs to be escaped in the replacement expression, meaning you need an extra two backslashes before the hyphen (and none after):

data = data.replaceAll("-", "\\\\-");

Better yet, don't use regex at all:

data = data.replace("-", "\\-");

Upvotes: 2

user207421
user207421

Reputation: 311050

The hyphen is only special in regular expressions when used to create ranges in character classes, e.g. [A-Z]. You aren't doing that here, so you don't need any escaping at all.

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30849

Try with \\\\- instead, e.g:

String data = "vale-cx";
System.out.println(data.replaceAll("\\-", "\\\\-"));

Upvotes: 0

Related Questions