Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java's Regex to extract a word from a path name

Tags:

java

regex

I have a directory like this and I am trying to extract the word "photon" from just before "photon.exe".

C:\workspace\photon\output\i686\diagnostic\photon.exe(Suspended) Thread(Running)

My code looks like this:

String path = "C:\workspace\photon\output\i686\diagnostic\photon.exe(Suspended) Thread(Running)";
Pattern pattern = Pattern.compile(".+\\\\(.+).exe");

Matcher matcher = pattern.matcher(path);

System.out.println(matcher.group(1));

No matter what permutations I try I keep getting IllegalStateExceptions etc, despite this regular expression working on http://www.regexplanet.com/simple/index.html.

Thanks in advance for any help. I am super frustrated at this point >.<

like image 443
user684586 Avatar asked Apr 11 '11 19:04

user684586


1 Answers

You need to actually run the matcher:

if ( matcher.find() ) {
    System.out.println(matcher.group(1));
}

Note that I use matcher.find() above instead of matcher.matches() because your regex is not set up to match the entire string (it won't match the (Suspended... part). Since that's the case, you don't really need the preamble to the slash; \\\\(.+).exe should work fine.

Of course, this is mentioned in the documentation for group(int):

Throws:

IllegalStateException - If no match has yet been attempted, or if the previous match operation failed

like image 168
Mark Peters Avatar answered Nov 03 '22 09:11

Mark Peters