match_pattern = "[\\?&;/](\\w+)=([^&;/]+)";p = Pattern.compile(match_pattern);tempStr="http://desk.myspace.com/html.ng/site=myspace&position=skyscraper&page=14000000&rand=8579377470&acnt=2&schoolpage=0";while((m = p.matcher(tempStr)) != null)
{
groupCount = m.groupCount();
for(i=1; i<=groupCount; i++)
{
if(m.find(i))
{
matchedStr = m.group(i);
}
} end = m.end();
tempStr = tempStr.substring(end);
}
我想取出所有"="前的参数名和后面的值,但是我这样执行的结果只得到第1,3,5这3对,第2,4,6被跳过了,不知道为啥.
还有个小问题[^h]表示匹配非h的串,那么匹配不包含http的串是(^http)吗?还是[^(http)]?
{
groupCount = m.groupCount();
for(i=1; i<=groupCount; i++)
{
if(m.find(i))
{
matchedStr = m.group(i);
}
} end = m.end();
tempStr = tempStr.substring(end);
}
我想取出所有"="前的参数名和后面的值,但是我这样执行的结果只得到第1,3,5这3对,第2,4,6被跳过了,不知道为啥.
还有个小问题[^h]表示匹配非h的串,那么匹配不包含http的串是(^http)吗?还是[^(http)]?
因为你的正则式用错了.下面是正确的用法:
-------------------------------------------
import java.util.regex.*;
/**
*利用正则式从网页中提取参数
*@author: Eastsun
*/
public class FindT{
public static void main(String[] args){
String match_pattern = "(?<=[&/])(\\w+?)=([\\d\\w]+?)(?=&|$)";
Pattern p = Pattern.compile(match_pattern); String tempStr="http://desk.myspace.com/html.ng/site=myspace&position=skyscraper&page=14000000&rand=8579377470&acnt=2&schoolpage=0";
Matcher m =p.matcher(tempStr);
while(m.find()){
System.out.println("参数: "+m.group(1)+",值: "+m.group(2));
}
}
}
----------------------------------------------------------
程序运行结果:
参数: site,值: myspace
参数: position,值: skyscraper
参数: page,值: 14000000
参数: rand,值: 8579377470
参数: acnt,值: 2
参数: schoolpage,值: 0
第二个问题:
[^(http)]表示:这个字符不能是(,h,t,p,)这5个.
还有个问题:我要是想匹配不带http的字符串应该怎么写?谢谢~
(?!http)\\w{4}
你问得问题有点笼统,具体问题具体对待吧.
String[] sa = tempStr.split("&");
for (int i = 1; i < sa.length; i++) {
String[] sa1=sa[i].split("=");
System.out.println(sa1[0]+": "+sa1[1]);
}
}
}结果:
position: skyscraper
page: 14000000
rand: 8579377470
acnt: 2
schoolpage: 0
http123
123htttp
123http
可以匹配第二行,1和3行由于带http串而不可以匹配,这个正则应该怎么写?
经我试验将一楼的正则表达式换成String match_pattern = "(\\w+)=([\\d\\w]+)";
也可以。
请问"(?<=[&/])(\\w+?)=([\\d\\w]+?)(?=&|$)";中(?<=[&/])和(?=&|$)中的?<=,?=是什么意思?还有按我对加括号分组的理解String match_pattern = "(\\w+)=([\\d\\w]+)";中1,2组是想要的结果,可是1楼"(?<=[&/])(\\w+?)=([\\d\\w]+?)(?=&|$)"中1,2组也是想要的结果,好神奇,按我理解1楼的2,3组才是呀。
http123
123htttp
123http
可以匹配第二行,1和3行由于带http串而不可以匹配,这个正则应该怎么写?