使用正则表达式java的规则

时间:2011-11-07 15:18:18

标签: java regex

我有模式:

host=([a-z0-9./:]*)

它找到了我的主机地址。我有content

host=http//:sdf3452.domain.com/

我的代码是:

    Matcher m;
    Pattern hostP = Pattern.compile("host=([a-z0-9./:]*)");
    m=hostP.matcher(content);//string 1
    String match = m.group();//string 2 
    Log.i("host", ""+hostP.matcher(content).find());

如果删除字符串1和2,我会在true中看到logcat。如果离开,我得到的例外没有找到。 我尝试了各种pattern。通过debug查看m变量,找不到匹配项。请教我使用reg exp!

2 个答案:

答案 0 :(得分:4)

group()匹配之前,您需要调用find()

试试这样:

Pattern hostP = Pattern.compile("host=([a-z0-9./:]*)");
Matcher m = hostP.matcher(content);

if(m.find()) {
  String match = m.group();
  // ... 
}

修改

和一个小型演示,显示每个匹配组包含的内容:

Pattern p = Pattern.compile("host=([a-z0-9./:]*)");
Matcher m = p.matcher("host=http://sdf3452.domain.com/");
if (m.find()) {
  for(int i = 0; i <= m.groupCount(); i++) {
    System.out.printf("m.group(%d) = '%s'\n", i, m.group(i));
  }
}

将打印:

m.group(0) = 'host=http://sdf3452.domain.com/'
m.group(1) = 'http://sdf3452.domain.com/'

如您所见,group(0)与group()相同,包含整个模式匹配的内容。

但要意识到,网址可以包含的内容远远超过[a-z0-9./:]*中定义的内容!

答案 1 :(得分:0)

String content = "host=http://sdf3452.domain.com/";


Matcher mm;
Pattern hostP = Pattern.compile("host=([a-z0-9./:]*)");
mm=hostP.matcher(content);
String match = "";
if (mm.find()){//use m.find() first
    match = mm.group(1);//1 is order number of brackets 
}