我试图在我的Java代码中设置一个REGEX,其中任何以.exe等特定表达式结尾的给定字符串都应为布尔值true,否则应返回false。正则表达式应该是什么?
答案 0 :(得分:0)
您甚至不需要正则表达式,只需使用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");
}
答案 1 :(得分:0)
在这里,我们可能想在右侧创建一个捕获组,并使用逻辑OR将我们喜欢的任何扩展名添加到其中,然后向左滑动并收集文件名,也许类似于:
^(.*\.)(exe|mp3|mp4)$
在这种情况下就是:
^(.*\.)(exe)$
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));
}
}
此代码段仅显示捕获组的工作方式:
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可视化正则表达式: