Java 一个正则表达式,可用于两个不同的字符串url';s

Java 一个正则表达式,可用于两个不同的字符串url';s,java,regex,Java,Regex,控制台中的输出将被打印为group(1)=gar,和group(2)=garmin first,但我真正需要的是一个可以同时适用于这两种情况的正则表达式。另一种情况是: public String getContextName() { String contextName = FacesContext.getCurrentInstance() .getExternalContext().getRequestContextPath();

控制台中的输出将被打印为
group(1)=gar
,和
group(2)=garmin first
,但我真正需要的是一个可以同时适用于这两种情况的正则表达式。另一种情况是:

public String getContextName() {
    String contextName = FacesContext.getCurrentInstance()
                         .getExternalContext().getRequestContextPath();
    String uri = "localhost/gar/garmin-first/gar_home";
    Pattern pat=Pattern.compile("/(.*?)/(.*)/");
    Matcher matcher = pat.matcher(uri);
    matcher.find();
    System.out.println("matched"+matcher.group(1)+matcher.group(2));
    if (StringUtil.isNotEmpty(contextName) && 
        contextName.contains(matcher.group(1))) {

        return matcher.group(2);
    }
    return matcher.group(1);
}
在这种情况下,我需要输出为
group(1)=garmin first
,并且
group(2)
应该保留为空。你能帮帮我吗 请使用能同时适用于这两种情况的正则表达式。

包测试;
String uri = "localhost/garmin-first/gar_home";
导入java.util.regex.Matcher; 导入java.util.regex.Pattern; 公共类Test1 { 公共静态void main(字符串[]args) { 字符串[]字符串=新字符串[] {“localhost/gar/garmin first/garu home”、“localhost/garmin first/garu home”};
Pattern pat=Pattern.compile((?):首先感谢您的回答,对于任何可以派生的URL类型,如字符串contextName=FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();字符串uri=((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURI());,因为使用它的主要原因是为了性能调整。它适用于任何字符串组合,您只需注意返回的内容。a/b/c/d返回b&c,a/b/c/d/将返回b,c&d。如果您的路径变得更深,它也将返回其他路径。(a/b/c/d/e/f将返回b,c,d&e):在我们的应用程序中增加了一个要求,我们提供的正则表达式也应接受大写字母。不幸的是,在我们的情况下,它不接受该要求。是否有任何方法可以帮助我们解决当前正则表达式中的修改问题。谢谢
package test;

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

public class Test1
{
    public static void main(String[] args)
    {
        String[] strings = new String[]
        { "localhost/gar/garmin-first/gar_home", "localhost/garmin-first/gar_home" };
        Pattern pat = Pattern.compile("(?<=/)(.*?)(?=/)");
        for(String s : strings)
        {
            System.out.println("For: " + s);
            Matcher matcher = pat.matcher(s);
            while (matcher.find())
            {
                System.out.println(matcher.group());
            }
        }
    }
}