Java 不会替换所有字符串,因为标签旁边有文本(post 已改进)

Java won't replace all strings, because there is text next to the tags (post improved)

我正在开发一个程序,它格式化从 PDF 文件中提取的 HTML 代码。 我有一个字符串列表,其中包含段落并除以该段落。 由于 PDF 有超链接,我决定用脚注编号“[1]”替换它们。 这将用于引用来源。我最终会计划将其放在段落或句子的末尾,这样您就可以像在书中一样查找资料来源。

我的问题
由于某种原因,并不是所有的超链接都被替换了。 原因很可能是标签旁边有文字。

Hell<a href="http://www.example.com">o old chap!

特别是“o”部分和“hell”部分正在阻止 java .replaceAll 函数执行它的工作。

预期结果

Hello [1] old chap!

编辑: 如果我只是在 URL 之前和之后添加 space,它可能会将一些词(如“help”)拆分为“help p”,这也不是一个选项。

我的代码必须替换 URL 标签(没有 )并且不创建新的额外 spaces。

这是我的一些代码,出现问题的地方:

for (int i = 0; i < EN.length; i++) {
        Pattern pattern_URL = Pattern.compile("<a(.+?)\">", Pattern.DOTALL);
        Matcher matcher_URL = pattern_URL.matcher(EN[i]); //Checks in the curren Array part.

        if (matcher_URL.find() == true) {
            source_number++;
            String extractedURL = matcher_URL.group(0);
            //System.out.println(extractedURL);
            String extractedURL_fully = extractedURL.replaceAll("href=\"", ""); //Anführungszeichen
            //System.out.println(extractedURL_fully);

            String nobracketURL = extractedURL.replaceAll("\)", ""); //Remove round brackets from URL

            EN[i] = EN[i].replaceAll("\)\"", "\""); /*Replace round brackets from URL in Array. (For some reasons there have been href URLs, with an bracket at the end. This was already in the PDF. They were causing massive problems, because it didn't comment them out, so the entire replaceAll command didn't function.)*/
            EN[i] = EN[i].replaceAll(nobracketURL, "[" + source_number + "]"); //Replace URL tags with number and Edgy brackets
        }
        else{
            //System.out.println("FALSE: " + "[" + i + "]");

        }



    }

整个想法是,它循环遍历数组并替换所有 URLs,包括它的起始标记 的末尾(也可以看到在模式正则表达式中。)

如果我错了请纠正我,但您需要的是从给定字符串中删除所有 <a> 标记,对吗?如果是这种情况,您需要做的就是使用如下代码:

final String string = "<a href=\"http://www.example.com\">Sen";

final Pattern pattern = Pattern.compile("<a(.+?)>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll("");

System.out.println(result); // prints "Sen"

请注意,我没有使用 String 对象中的 replaceAll,而是 Matcher 对象中的。这将替换空字符串“”的所有匹配项。