gpt4 book ai didi

Java正则表达式在两个模式之间匹配

转载 作者:行者123 更新时间:2023-11-30 05:21:33 24 4
gpt4 key购买 nike

我有一个像

这样的网址
https://example.com/helloworld/@.id==imhere 

https://example.com/helloworld/@.id==imnothere?param1=value1

我想提取值imhereimnothere来自这些 URL。

Pattern.compile("(?<=helloworld\\/@\\.id==).*(?=\\?)"); 

这个问题是没有找到吗? (第一种情况)它与模式不匹配。

有人可以帮我解决这个问题吗?抱歉我的错误,我错过了 URL 中的 @.id 阶段。

最佳答案

这个表达式应该可以做到:

^.*@==(.*?)(?:\?.*)?$ 

regex101 demo

它搜索@==并获取该字符串之后的所有内容,直到?(如果有)。诀窍是懒惰的*

实际比赛在第一组进行。转换为 Java 后,示例应用程序将如下所示:

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

class Sample {
private static final String PATTERN_TEMPLATE = "^.*@==(.*?)(?:\\?.*)?$";

public static void main (final String... args) {
final Pattern pattern = Pattern.compile(PATTERN_TEMPLATE);

final String firstTest = "https://example.com/helloworld/.@==imhere";
final Matcher firstMatcher = pattern.matcher(firstTest);
if (firstMatcher.matches()) {
System.out.println(firstMatcher.group(1));
}

final String secondTest =
"https://example.com/helloworld/.@==imnothere?param1=value1";
final Matcher secondMatcher = pattern.matcher(secondTest);
if (secondMatcher.matches()) {
System.out.println(secondMatcher.group(1));
}
}
}

Ideone demo

如果想合并正则表达式来验证 helloworld/. 是否存在,那么可以简单地扩展正则表达式:

^.*helloworld\/\.@==(.*?)(?:\?.*)?$

regex101 demo

但是将这个表达式翻译成 Java 时应该小心。必须转义反斜杠。

关于Java正则表达式在两个模式之间匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493401/

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