两种模式之间的Java正则表达式匹配

两种模式之间的Java正则表达式匹配,java,regex,Java,Regex,我有一个类似的url https://example.com/helloworld/@.id==imhere 或 我想从这些URL中提取值imhere或imnothere Pattern.compile("(?<=helloworld\\/@\\.id==).*(?=\\?)"); 这个的问题是它没有找到?第一种情况是,它与模式不匹配 有人能帮我修一下吗? 对不起,我犯了错误,我错过了URL中的@.id阶段。此表达式应该可以: ^.*@==(.*?)(?:\?.*)?$ 它搜索

我有一个类似的url

https://example.com/helloworld/@.id==imhere 

我想从这些URL中提取值imhere或imnothere

Pattern.compile("(?<=helloworld\\/@\\.id==).*(?=\\?)"); 
这个的问题是它没有找到?第一种情况是,它与模式不匹配

有人能帮我修一下吗?
对不起,我犯了错误,我错过了URL中的@.id阶段。

此表达式应该可以:

^.*@==(.*?)(?:\?.*)?$ 
它搜索@==并获取该字符串后面的所有内容,如果有的话,最大为a。诀窍在于懒惰*

实际比赛在第一组。转换为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正则表达式如下所示:


我不会为此使用正则表达式。这是一个简单问题的重量级解决方案

使用提取主机和?之间零件的路径(如果有),然后查找最后出现的==:


非常感谢你。由于我错过了URL中的“id”阶段,在将其添加到您的表达式中后,它对我起了作用。我必须使用短语helloworld,因此使用第二个表达式:^.*helloworld\\/@\\.id==.*?:\\?*?$欢迎您。请随意投票和/或将我的帖子标记为答案。
^.*helloworld\/\.@==(.*?)(?:\?.*)?$
String s = "https://example.com/helloworld/@.id==imnothere?param1=value1";

URI uri = URI.create(s);
String path = uri.getPath();
int idAttributeIndex = path.lastIndexOf("@.id==");
String id = path.substring(idAttributeIndex + 6);