user372743
user372743

Reputation:

Java Regex Arguments

So if I wished to replace all numbers with a given value, I could just use

"hello8".replaceAll("[1-9]", "!");

hello!

Now is there a way to get the number that is actually being matched and add that to the string?

e.g.

hello!8

Upvotes: 5

Views: 4944

Answers (3)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

You can do something like this

"hello8".replaceAll("([1-9])", "!$1");

See javadoc

Upvotes: 0

Java Guy
Java Guy

Reputation: 3441

Here you go!

String s = "hello8";
String y = null;
String t = null;
Pattern p = Pattern.compile("[1-9]");
Matcher m = p.matcher(s);
while(m.find()) {
    y = (m.group());
    t = "!"+y;
    s = s.replace(y.toString(), t.toString());
}
System.out.println(s);

Upvotes: 0

Kobi
Kobi

Reputation: 138007

One option is to set a capturing group:

"hello8".replaceAll("([1-9])", "!$1");

Another option is to use $0, which means the whole match:

"hello8".replaceAll("[1-9]", "!$0");

See also: regular-expressions.info/java

Upvotes: 6

Related Questions