0

I am trying to setup a REGEX in my java code where any given string ending with a particular expression like .exe should give a boolean true value else if should return false value. What should be the regex expression.?

Su So
  • 168
  • 1
  • 3
  • 12

2 Answers2

1

You don't even need regex for this, just use String#endsWith:

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

If you wanted to use regex, you could use String#matches here:

String file = "some_file.exe";
if (file.matches(".*\\.exe")) {
    System.out.println("MATCH");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • The above given solutions are returning MATCH if i am giving some_file.exe.exe ., I don't want that,, i want it should return false for .exe , abc.exe.exe and true for azbc.exe. – Su So May 23 '19 at 05:41
  • I don't understand your logic. Can you explain it better, _in your original question_, and _not_ here as comment? – Tim Biegeleisen May 23 '19 at 05:41
1

Here, we might want to create a capturing group on the right and add any extensions that we like in it using logical ORs, then swipe to left and collect the filenames, maybe similar to:

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

which in this case would be just:

^(.*\.)(exe)$

DEMO

Test

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));
    }
}

Demo

This snippet just shows that how the capturing groups work:

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}`);
    });
}

RegEx

If this expression wasn't desired, it can be modified or changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69