Using Java Regex to Extract a Word from a Path Name

I have such a directory and I am trying to extract the word "photon" immediately before "photon.exe".

C: \ workspace \ photon \ output \ i686 \ diagnostic \ photon.exe (suspended) Subject (work)

My code is as follows:

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 regex working on http://www.regexplanet.com/simple/index.html .

Thanks in advance for any help. At this moment, I am very upset>. <

+5
source share
4 answers

: ^.*\\(.*)\.exe.*$ . .

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{
    public static void main(final String[] args)
    {
        final String input = args[0];
        final Pattern pattern = Pattern.compile("^.*\\\\(.*)\\.exe.*$");
        final Matcher matcher = pattern.matcher(input);
        if (matcher.find())
        {
            System.out.println("matcher.group(1) = " + matcher.group(1));
        }
        else
        {
            System.out.format("%s does not match %s\n", input, pattern.pattern());
        }
    }
}

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

matcher.group(1) = photon
+2

:

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

, matcher.matches() matcher.matches() matcher.find(), ( (Suspended...). ; \\\\(.+).exe .

, group(int):

:

IllegalStateException - ,

+7

(new java.io.File("C:\workspace\photon\output\i686\diagnostic\photon.exe(Suspended) Thread(Running)")).getName().split("\\.")[0];

0

: [\\d\\w]+\\.exe

, .

Another option is to use .+\\.exeto get the full file name and use substringand lastIndexOf('\')to get the file name.
You can also use new File(fullFilePath).getFileName()which is the more correct way to do this, since it will save you substring- but I don't know if it has the best performance.

0
source

All Articles