我有一个像
这样的网址https://example.com/helloworld/@.id==imhere
或
https://example.com/helloworld/@.id==imnothere?param1=value1
我想提取值imhere
或imnothere
来自这些 URL。
Pattern.compile("(?<=helloworld\\/@\\.id==).*(?=\\?)");
这个问题是没有找到吗? (第一种情况)它与模式不匹配。
有人可以帮我解决这个问题吗? 抱歉我的错误,我错过了 URL 中的 @.id 阶段。
最佳答案
这个表达式应该可以做到:
^.*@==(.*?)(?:\?.*)?$
它搜索@==
并获取该字符串之后的所有内容,直到?
(如果有)。诀窍是懒惰的*
。
实际比赛在第一组进行。转换为 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));
}
}
}
如果想合并正则表达式来验证 helloworld/.
是否存在,那么可以简单地扩展正则表达式:
^.*helloworld\/\.@==(.*?)(?:\?.*)?$
但是将这个表达式翻译成 Java 时应该小心。必须转义反斜杠。
关于Java正则表达式在两个模式之间匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493401/