Skip to content
Advertisement

Replace word outside regex

Is it possible to make a replacement in an inverted way, where the regular expression is maintained and the other characters are eliminated?

Word String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";

Regex

([0-9]{2}/[0-9]{2}/[0-9]{4})

word.replaceAll("([0-9]{2}/[0-9]{2}/[0-9]{4})","");

Expected

27/08/2020

Advertisement

Answer

Yes, it’s called find().

String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";

Matcher m = Pattern.compile("([0-9]{2}/[0-9]{2}/[0-9]{4})").matcher(word);
if (m.find())
    System.out.println(m.group());

Output

27/08/2020

Alternative, make the regex match everything, and use the capture group you already defined:

word.replaceFirst(".*?([0-9]{2}/[0-9]{2}/[0-9]{4}).*", "$1")

Result

27/08/2020

The main difference between the two if what happens of the regex doesn’t match, i.e. if the string doesn’t have a date in it.

The first will print nothing. You can explicitly control how you handle it by writing an else clause.

The second will result in the full original string, unchanged. You cannot control how you handle the “not found” condition.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement