Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何获取嵌套标记之间的字符串_Java_Beanshell - Fatal编程技术网

Java 如何获取嵌套标记之间的字符串

Java 如何获取嵌套标记之间的字符串,java,beanshell,Java,Beanshell,在项目中,我们尝试替换标记中的文本。 我们试图从html文件中获取带有beanshell的字符串 <code> var testString = "<a href='test/keyword/common'>Here is our keyword which should be replaced</a><img src='test/keyword/again'/> </code> var testString=” 现在只需替换a

在项目中,我们尝试替换标记中的文本。 我们试图从html文件中获取带有beanshell的字符串

<code>
var testString = "<a href='test/keyword/common'>Here is our keyword which should be replaced</a><img src='test/keyword/again'/>
</code>

var testString=”
现在只需替换
a
标记之间的关键字。 这在正则表达式、子字符串或其他方面可行吗?

在有限的情况下,您可以使用正则表达式来实现。不过,我建议使用诸如或之类的HTML解析/操作库。它将为您提供一个更健壮且(可能)更易读/理解的解决方案

public static void main(String[] args) {
        String string = "<code>var testString = <a href='test/keyword/common'>Here is our keyword which should be replaced</a><img src='test/keyword/again'/></code>";
        string = string.replaceAll("(<code>.*?)Here is our keyword which should be replaced(.*?</code>)","$1Replaced with:$2");
        System.out.println(string);
    }

试试这个:这正是您想要的,但我也建议您使用HTML解析器来解析HTML标记。

感谢JSoup的提示。是否可以只更改document.body.text而不丢失其中的所有HTML标记?