【问题标题】:REGEX to find .exe extension in a particular string.? [duplicate]正则表达式在特定字符串中查找 .exe 扩展名。? [复制]
【发布时间】:2019-05-23 13:15:46
【问题描述】:

我正在尝试在我的 java 代码中设置一个正则表达式,其中任何以特定表达式(如 .exe)结尾的给定字符串都应该给出一个布尔真值,否则如果应该返回假值。正则表达式应该是什么?

【问题讨论】:

  • 认真的吗?您应该只阅读 Pattern 的 javadocs。这个任务很简单......

标签: java regex jsp


【解决方案1】:

你甚至不需要正则表达式,只需使用String#endsWith

String file = "some_file.exe";
if (file.endsWith(".exe")) {
    System.out.println("MATCH");
}

如果你想使用正则表达式,你可以在这里使用String#matches

String file = "some_file.exe";
if (file.matches(".*\\.exe")) {
    System.out.println("MATCH");
}

【讨论】:

  • 如果我给出 some_file.exe.exe ,上面给出的解决方案将返回 MATCH 。我不希望这样,我希望它应该为 .exe 、 abc.exe.exe 和azbc.exe 为 true。
  • 我不明白你的逻辑。您能否更好地解释一下,在您的原始问题中,而不是在这里作为评论?
【解决方案2】:

在这里,我们可能希望在右侧创建一个捕获组,并使用逻辑 OR 在其中添加我们喜欢的任何扩展名,然后向左滑动并收集文件名,可能类似于:

^(.*\.)(exe|mp3|mp4)$

在这种情况下只是:

^(.*\.)(exe)$

DEMO

测试

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

final String regex = "^(.*\\.)(exe|mp3|mp4)$";
final String string = "anything_you_wish_here.exe\n"
     + "anything_you_wish_here.mp4\n"
     + "anything_you_wish_here.mp3\n"
     + "anything_you_wish_here.jpg\n"
     + "anything_you_wish_here.png";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

演示

这个 sn-p 只是显示了捕获组是如何工作的:

const regex = /^(.*\.)(exe|mp3|mp4)$/gm;
const str = `anything_you_wish_here.exe
anything_you_wish_here.mp4
anything_you_wish_here.mp3
anything_you_wish_here.jpg
anything_you_wish_here.png`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

正则表达式

如果不需要此表达式,可以在 regex101.com 中修改或更改。

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 2018-08-08
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    相关资源
    最近更新 更多