Mati
Mati

Reputation: 33

Replace a specific character in a regex match

How can I replace a specific character in a Regex match which is present multiple times.

I found this post about it which helped me a lot, but it replaces only 1 character. I would need it to replace all.

For example from this:

href="https://Link.com/test/Release+This+Has+Some+Pluses
Linkcom//test/Release+This+Has+Some+Pluses

To:

href="https://Link.com/test/Release%20This%20Has%20Some%20Pluses
Link.com/test/Release+This+Has+Some+Pluses

Here is what I got so far

Line.replaceAll("(https://Link.com/test/)(\w+)\+" , "$1%20")

But as I already mentioned. This only replaces one character and not all like this:

href="https://Link.com/display/release5/Release%20This+Has+Some+Pluses
Link.com/test/Release+This+Has+Some+Pluses

How would I replace all?

EDIT

Here is the code snippet from Java:

public class ExchangeLink {

    public static void main(String[] args) {
        try {
            Path path = Paths.get("C:\\Users\\Mati\\Desktop\\test.txt");
            Stream<String> lines = Files.lines(path);
            List<String> replaced = lines.map(line -> line.replaceAll("(href=\"https://link.com/test/)(\\w+)\\+", "$1$2%20")).collect(Collectors.toList());
            Files.write(path, replaced);
            lines.close();
            System.out.println("Find and Replace done!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 2

Views: 143

Answers (1)

maraca
maraca

Reputation: 8743

Just do it in 2 steps.

Pattern links = Pattern.compile("href=\"https://link.com/test/((\\w+)\\+?)+");
Matcher matcher = links.matcher(line);
while (matcher.find()) {
    line = line.replace(matcher.group(), matcher.group().replace("+", "%20"));
}

Upvotes: 1

Related Questions