在java中使用regex获取特定字符串

时间:2010-04-01 05:17:39

标签: java regex

我想如何使用正则表达式或任何其他方法从字符串获取唯一链接的代码。

以下是java代码:

String aas =  "window.open("+"\""+"http://www.example.com/jscript/jex5.htm"+"\""+")"+"\n"+"window.open("+"\""+"http://www.example.com/jscript/jex5.htm"+"\""+")";

如何获取链接http://www.example.com/jscript/jex5.htm

谢谢并提前

2 个答案:

答案 0 :(得分:0)

正则表达式

(?<=window.open\(")[^"]*(?="\))

匹配您给出的字符串中的链接。正确地逃脱了它的读取

"(?<=window.open\\(\")[^\"]*(?=\"\\))"

答案 1 :(得分:0)

这将打印出以“http://”开头的字符串中包含的第一个URL:

  public static void main(String[] args) throws Exception {
    String javascriptString = "window.open(" + "\"" + "http://www.example.com/jscript/jex5.htm" + "\"" + ")" + "\n" + "window.open(" + "\""
        + "http://www.example.com/jscript/jex5.htm" + "\"" + ")";

    Pattern pattern = Pattern.compile(".*(http://.*)\".*\n.*");
    Matcher m = pattern.matcher(javascriptString);

    if (m.matches()) {
      System.out.println(m.group(1));
    }
  }