简体   繁体   English

替换正则表达式匹配中的特定字符

[英]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.我发现这篇关于它的帖子对我有很大帮助,但它只替换了 1 个字符。 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:这是来自 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();
        }
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM