Kyle Bridenstine
Kyle Bridenstine

Reputation: 6383

Java simple regex with hyphen

I'm trying to do something seemingly simple. I have meta-data with this format

    -key=value

I've already split the string at the = but I need to take the - off. I'm trying to use this function key.replaceFirst("-", ""); but it doesn't do anything to the string.

I've tried putting \\ in the regex but that solved nothing.

Solution:

I did not say key = key.replaceFirst("-", "");

Upvotes: 2

Views: 84

Answers (3)

falsetru
falsetru

Reputation: 369074

String.replaceFirst does not replace the string in-place, but returns a replaced string.

You need to assign back the return value:

key = key.replaceFirst("-", "");

Upvotes: 3

Keshava
Keshava

Reputation: 802

You are not assigning the string back to it !

key = key.replaceFirst("-", "");
System.out.println(key);

HTH, Keshava.

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You need to assign back return value of replaceFirst as String is immutable object:

key = key.replaceFirst("-", "");

Upvotes: 4

Related Questions