2016-02-20 72 views
1

我想用Java中的<a href="link">text</a>代替[text](link)。我怎样才能做到这一点?如何在java中使用<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(); 
} 

这是更好,因为使用全部匹配文字。

回答

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); 
     } 
    } 

这将为任何 “文本” 工作,任何“链接“

查看演示here

+0

@insidefun考虑投票的答案,这是SO的方式“谢谢你”:) – SmokeDispenser

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>"; 
+0

这将工作,当且仅当字符串只是[文本](链接) – SomeDude