5

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

0

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

You can do something like this

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

See javadoc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.