繁体   English   中英

Java正则表达式模式问题

[英]Java regex pattern issue

我有一个字符串:

bundle://24.0:0/com/keop/temp/Activator.class

从这个字符串中,我需要获取com/keop/temp/Activator但是需要以下模式:

Pattern p = Pattern.compile("bundle://.*/(.*)\\.class"); 

仅返回Activator 我的错误在哪里?

您的正则表达式使用贪心匹配和. 匹配任何字符(但换行符)。 .*/读取所有内容,直到最后一个/(.*)\\\\. 匹配直到最后期限的所有内容。 除了懒惰匹配,您可以将要匹配的字符限制为非/然后再匹配要匹配的字符串。 改成

Pattern p = Pattern.compile("bundle://[^/]*/(.*)\\.class"); 

样例代码:

String str = "bundle://24.0:0/com/keop/temp/Activator.class";
Pattern ptrn = Pattern.compile("bundle://[^/]*/(.*)\\.class");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
   System.out.println(matcher.group(1));

示例程序的输出:

com/keop/temp/Activator

您需要在初始标记.*加上? 进行非贪婪的比赛。

bundle://.*?/(.*)\\.class
           ^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM