1

I have a string: "Foo value 1.1.1".

I want to replace the 1.1.1 with something else, say ***?

I tried str.replaceAll("[0-9].[0-9].[0-9]", "***") and it works, but the word 1.1.1 can change and be "1.1" or "1.1.a" or "111", etc.

This word is always followed by the word "value" though. Thus I basically want to replace the word that comes after value, how can I do it using replaceAll.

2 Answers 2

2

You can use regex like (value\s)([\w\.?]+) to match and group it,then use $1 and $2 to replace it.

In your case,$1 represent for vaule\s and $2 represent [\w\.]+,we just need to reserve $1 and replace $2

    String str1 = "Foo value 1.1.1".replaceAll("(value\\s)([\\w\\.?]+)", "$1AAA");
    String str2 = "Foo value 1.1".replaceAll("(value\\s)([\\w\\.?]+)", "$1BBB");
    String str3 = "Foo value Stackoverflow".replaceAll("(value\\s)([\\w\\.?]+)", "$1CCC");
    System.out.println(str1);//output: Foo value AAA
    System.out.println(str2);//output: Foo value BBB
    System.out.println(str3);//output: Foo value CCC

Update,an more elegant way is to change regex to (?<=value\s)[\w\.?]+,output will be the same

String str1 = "Foo value 1.1.1".replaceAll("(?<=value\\s)[\\w\\.?]+", "AAA");
String str2 = "Foo value 1.1".replaceAll("(?<=value\\s)[\\w\\.?]+", "BBB");
String str3 = "Foo value Stackoverflow".replaceAll("(?<=value\\s)[\\w\\.?]+", "CCC");
System.out.println(str1);//output: Foo value AAA
System.out.println(str2);//output: Foo value BBB
System.out.println(str3);//output: Foo value CCC
Sign up to request clarification or add additional context in comments.

Comments

1

Or, just to try something new :-p - you could try using a "positive lookbehind":

groovy:000> a = "hello there Moi"
groovy:000> p = java.util.regex.Pattern.compile("(?<=there\\s)\\w+")
groovy:000> m = p.matcher(a)
groovy:000> m.replaceAll("John")
===> hello there John

The regular expression (?<=there\\s)\\w+ will match any word, if it is preceded by "there " (with any whitespace character, not just space, after "there")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.