gpt4 book ai didi

java - 一个可用于两个不同字符串 url 的正则表达式

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:03 25 4
gpt4 key购买 nike

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) = gar, and group(2) = garmin-first,但我真正需要的是一个适用于这两种情况的正则表达式。另一种情况是:

String uri = "localhost/garmin-first/gar_home";

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

最佳答案

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());
}
}
}
}

我巧妙地更改了正则表达式,以便我们寻找被“/”包围的单词。希望您能找到一种有用的方法来获取所需的部分,因为我认为 .group(1) 和 .group(2) 现在不会起作用,因为我们正在寻找同一字符串中的多个匹配项。

关于java - 一个可用于两个不同字符串 url 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8250176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com