Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing regex with the same amount of "." as its length

Tags:

java

regex

See this for my current attempt: http://regexr.com?374vg

I have a regex that captures what I want it to capture, the thing is that the String().replaceAll("regex", ".") replaces everything with just one ., which is fine if it's at the end of the line, but otherwise it doesn't work.

How can I replace every character of the match with a dot, so I get the same amount of . symbols as its length?

like image 217
Schadenfreude Avatar asked Jan 30 '26 11:01

Schadenfreude


2 Answers

Here's a one line solution:

str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");

Here's some test code:

String str = "foo bar COG-2134 baz";
str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");
System.out.println(str);

Output:

foo bar ........ baz
like image 138
Bohemian Avatar answered Feb 01 '26 01:02

Bohemian


This is not possible using String#replaceAll. You might be able to use Pattern.compile(regexp) and iterate over the matches like so:

StringBuilder result = new StringBuilder();
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(inputString);
int previous = 0;
while (matcher.find()) {
    result.append(inputString.substring(previous, matcher.start()));
    result.append(buildStringWithDots(matcher.end() - matcher.start()));
    previous = matcher.end();
}
result.append(inputString.substring(previous, inputString.length()));

To use this you have to define buildStringWithDots(int length) to build a String containing length dots.

like image 25
Markus Kreusch Avatar answered Feb 01 '26 02:02

Markus Kreusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!