如何替换:[text](链接)与java中的<a href="link">text</a>?

时间:2016-02-20 00:33:40

标签: java android regex pattern-matching

我想用Java中的[text](link)替换<a href="link">text</a>。我怎么能这样做?

在objective-c中,它看起来像:

NSRegularExpression *linkParsing = [NSRegularExpression regularExpressionWithPattern:@"(?<!\\!)\\[.*?\\]\\(\\S*\\)" options:NSRegularExpressionCaseInsensitive error:nil];

修改

最后,基于svasa's方法,我确实喜欢这样:

public String parseText(String postText) {

    Pattern p = Pattern.compile("\\[(.*)\\]\\((.*)\\)");
    Matcher m = p.matcher(postText);

    StringBuffer sb = new StringBuffer(postText.length());

    while (m.find()) {
        String found_text = m.group(1);
        String found_link = m.group(2);
        String replaceWith = "<a href=" + "\"" + found_link + "\"" + ">" + found_text + "</a>";
        m.appendReplacement(sb, replaceWith);
    }

    return sb.toString();
}

最好,因为在文字中使用所有匹配。

2 个答案:

答案 0 :(得分:0)

试试这个:

String string = "[text](link)";
String text = string.substring(string.indexOf("[")+1, string.indexOf("]"));
String link = string.substring(string.indexOf("(")+1, string.indexOf(")"));
String result = "<a href=\""+link+"\">"+text+"</a>";

或更短一些:

String string = "[text](link)";
String result = "<a href=\""+string.substring(string.indexOf("(")+1, string.indexOf(")"))+"\">"+string.substring(string.indexOf("[")+1, string.indexOf("]"))+"</a>";

答案 1 :(得分:0)

你可以这样做:

public static void main (String[] args) throws java.lang.Exception
    {
        Pattern p = Pattern.compile( "\\[(.*)\\]\\((.*)\\)");
        String input = "I got  some [text](link) here";
        Matcher m = p.matcher( input );
        if( m.find() )
        {
            String found_text =  m.group(1);
            String found_link =  m.group(2);
            String replaceWith = "<a href=" + "\"" + found_link + "\"" + ">" + found_text + "</a>" ;
            input = input.replaceAll("\\[(.*)\\]\\((.*)\\)", replaceWith );
            System.out.println( input );
        }
    }

这适用于任何&#34;文字&#34;和任何&#34;链接&#34;

请参阅演示here

相关问题