我有一个这样的目录,我正试图从“photon.exe”之前提取单词“photon”。
C:\workspace\photon\output\i686\diagnostic\photon.exe(挂起)线程(运行)
我的代码是这样的:
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));
无论我尝试什么排列,我总是得到 IllegalStateExceptions 等,尽管这个正则表达式在 http://www.regexplanet.com/simple/index.html 上工作.
在此先感谢您的帮助。在这一点上我非常沮丧 >.<
最佳答案
您需要实际运行匹配器:
if ( matcher.find() ) {
System.out.println(matcher.group(1));
}
请注意,我在上面使用 matcher.find()
而不是 matcher.matches()
因为您的正则表达式未设置为匹配整个字符串(它不会t 匹配 (Suspended...
部分)。既然如此,您实际上并不需要斜杠的序言;\\\\(.+).exe
应该可以正常工作。
当然the documentation for group(int)
中提到了这个:
Throws:
IllegalStateException
- If no match has yet been attempted, or if the previous match operation failed
关于java - 使用 Java 的正则表达式从路径名中提取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5626583/