URIの自動リンクをするプログラムは例えば次のようになります。正規表現を使った簡易バージョンですし、複数のURIがテキストに指定されているとうまく動作しません。
import java.util.regex.Pattern;
public class App {
private String regexp = "(https?://[a-zA-Z0-9;/?:@&=\\+$,\\-_\\.!~*'\\(\\)%#]+)";
private String toHtml(String target) {
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(target);
target = target.replace("&", "&").replace("<", "<").replace(">",
">").replace("\"", """);
while (matcher.find()) {
String uri = matcher.group(1);
target = target.replace(uri, "<a href='" + uri + "'>" + uri
+ "</a>");
}
return target;
}
public void exec(String target) {
System.out.println(toHtml(target));
}
public static void main(String[] args) {
String target = "サンプル1 http://www.sssg.org/ … ";
App app = new App();
app.exec(target);
}
}
実行結果は次の通り。