gpt4 book ai didi

java - 使用 Java 的正则表达式从路径名中提取单词

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:44 25 4
gpt4 key购买 nike

我有一个这样的目录,我正试图从“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com