正则表达式在第一个">"之后删除内容

时间:2014-04-23 19:26:12

标签: java regex

正则表达式首先删除内容">"在下面的字符串中。在第一个">"之后放置任何东西。在另一个字符串中。

例如:

String input = <img alt="" src="http://abchdfgjd.com/-430.jpg" width="650" height="430" /> Have you seen <a href="http://www.funnyordie.com/between_two_ferns" target="_blank">Between Two Ferns</a>?

期望的输出:

ans1 = <img alt="" src="http://abchdfgjd.com/-430.jpg" width="650" height="430" />

ans2 = Have you seen <a href="http://www.funnyordie.com/between_two_ferns" target="_blank">Between Two Ferns</a>?

有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:2)

为什么不呢:

String fixed = original.substring(0, original.indexOf(">"));

如果您想加入>,那么只需+1 indexOf支票。

在此之后获取所有内容:

String after = original.substring(original.indexOf(">") + 1, original.length());

答案 1 :(得分:0)

除非我误解了你的问题,否则应该这样做(使用indexOf

public static void main(String[] args) throws IOException {
    String input = "<img alt=\"\" src=\"http://abchdfgjd.com/justin-bieber-ferns-650-430.jpg\" "
            + "width=\"650\" height=\"430\" /> Have you seen <a href=\"http://www.funnyordie.com/between_two_ferns\" "
            + "target=\"_blank\">Between Two Ferns</a>?";
    int pos = input.indexOf(">");
    String ans1 = input;
    String ans2 = "";
    if (pos > -1) {
        ans1 = input.substring(0, pos + 1);
        ans2 = input.substring(pos + 2);
    }
    System.out.println("ans1: " + ans1);
    System.out.println("ans2: " + ans2);        
}

输出

ans1: <img alt="" src="http://abchdfgjd.com/justin-bieber-ferns-650-430.jpg" width="650" height="430" />
ans2: Have you seen <a href="http://www.funnyordie.com/between_two_ferns" target="_blank">Between Two Ferns</a>?

答案 2 :(得分:0)

Regexp不是解析HTML的好主意。但是简单的字符串函数,比如split / indexOf,将以更简单的方式解决当前任务。

仍有正则表达式解决方案可用:

String input = "<img alt=\"\" src=\"http://abchdfgjd.com/justin-bieber-ferns-650-430.jpg\" width=\"650\" height=\"430\" /> Have you seen <a href=\"http://www.funnyordie.com/between_two_ferns\" target=\"_blank\">Between Two Ferns</a>?";

Pattern pattern = Pattern.compile("(<[^>]*>)(.*)");
Matcher m = pattern.matcher(input);

if (m.find()) {
    String ans1 = m.group(1);
    String ans2 = m.group(2);
    System.out.println(ans1);
    System.out.println(ans2);
}