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

标签 java regex

我有一个像

这样的网址
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/

相关文章:

java - 如何使用json对象名作为增量值?

ruby - 包含字符串的第一行(仅)的正则表达式

regex - Linux - 在路径中的每个斜杠后查找与正则表达式匹配的结果

java - 我们可以在不运行单独的 ignite 集群的情况下将 Apache ignite 与 spring 应用程序一起使用吗

java - 如何实现 OnFragmentInteractionListener?

java - 使用非静态方法而不将其引用到对象?

java - 跟踪外部 Java GUI 中的事件

regex - 即使匹配不需要,VBScript 正则表达式也会填充子匹配

"everything except 34,37"的正则表达式没有否定前瞻

c# - 正则表达式使用换行符拆分字符串(除非它在双引号之间)