简体   繁体   中英

Java regex pattern issue

I have a string:

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

And from this string I need to get com/keop/temp/Activator but the following pattern:

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

returns only Activator . Where is my mistake?

Your regex uses greedy matching with a . that matches any character (but a newline). .*/ reads everything up to the final / , (.*)\\\\. matches everything up to the final period. Instead of lazy matching, you can restrict the characters matched to non- / before the string you want to match. Change to

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

Sample code:

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));

Output of the sample program :

com/keop/temp/Activator

You need to follow the initial token .* with ? for a non-greedy match.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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