url匹配的正则问题


一个url,如 http://xxx/xxx/xx/xx/x/x/xxx/x/xx/xx.html
如何匹配出url中还有某个关键词的介于/和/之间的路径
比如: http://www.abc.com/2d/df/usnsdp_fun/sdkw.html
检索关键词fun,最后匹配出usnsdp_fun(整个url中关键词有且只有一个)

java 正则表达式

一代阿迪王 9 years, 7 months ago

public static void main(String[] args){
Pattern p = Pattern.compile("\\w*fun\\w*");
Matcher m = p.matcher(" http://www.abc.com/2d/df/usnsdp_fun/sdkw.html ");
if (m.find()){
System.out.println(m.group());
}
}

java的,没做过多测试,楼主再测测,这里\w包括数字字母及下划线,不包括斜杠,\w后有星号的,不知道为什么显示不出来

此ID被屏蔽 answered 9 years, 7 months ago

/^\/\w+fun\/$/

鞍马源自都 answered 9 years, 7 months ago

测试代码:


 java


 import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        System.out.println(getFun("http://www.abc.com/2d/df/usnsdp_fun/sdkw.html"));
        System.out.println(getFun("http://www.abc.com/2d/df/usnsdp_fun_abcd/sdkw.html"));
    }

    public static String getFun(String url) {
        Pattern p = Pattern.compile("[^/]*fun[^/]*");
        Matcher m = p.matcher(url);
        if (m.find()){
            return m.group();
        }
        return "";
    }
}

控制台输出:


 usnsdp_fun
usnsdp_fun_abcd

丨zero丨9 answered 9 years, 7 months ago

Your Answer