用于提取匹配字符串的开始和尾部的Java方法

时间:2017-04-20 06:24:23

标签: java jsp

我有如下字符串变量,

     <a....<imgtag/>...</a>

当foo中包含''时,我必须从foo中提取整个锚标记,否则不会。例如,从上面的例子我必须提取,

{{1}}

如何在java中有效地做到这一点?我知道我需要使用substring()和indexOf()。但我正在寻找有效的方法。有帮助吗?在此先感谢!!

2 个答案:

答案 0 :(得分:0)

您可以使用StringUtils类:

String substring=StringUtils.substringBetween("YOURSTRING", "<a", "</a>"); 

要使用StringUtils,您需要将apache commons lang jar添加到您的项目中(http://commons.apache.org/proper/commons-lang/

答案 1 :(得分:0)

我认为您可以使用正则表达式来解决问题:

public static void main(String[] args) {
    String foo = "someStringInPrefix<a....<imgtag/>...</a>";
    Pattern regex = Pattern.compile("<a[\\s\\S]*(<imgtag\\/>)+[\\s\\S]*</a>");
    Matcher regexMatcher = regex.matcher(foo);
    while(regexMatcher.find()){
        System.out.println(regexMatcher.group());
    }
}