2

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?

2 Answers 2

3

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

bundle://.*?/(.*)\\.class
           ^
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.