-1

I am creating a regex to support the following patterns

Documents/OneDrive/Collections/book.xlsx
Documents/OneDrive/Collections/book.xls
Documents/OneDrive/Collections/book.xlsm
book 2.xls
aa.xlsx

Attempt

^([a-zA-Z0-9 ]+[/])*([a-zA-Z0-9 ])
"+[.](xls[xm]?"   

This regex matches all the required patterns but how can i just limit to the last character.

Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

0

My guess is that you might want an expression similar to:

^(([a-z0-9\s]+\/)+)?([a-z0-9\s]+)\.[a-z]+

or:

^(([a-z0-9\s]+\/)+)?([a-z0-9\s]+)\.(xlsx?m?)$

Demo 1

Demo 2

Test

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

final String regex = "^(([a-z0-9\\s]+\\/)+)?([a-z0-9\\s]+)\\.[a-z]+";
final String string = "Documents/OneDrive/Collections/book.xlsx\n"
     + "Documents/OneDrive/Collections/book.xls\n"
     + "Documents/OneDrive/Collections/book.xlsm\n"
     + "book 2.xls\n"
     + "aa.xlsx\n\n";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
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));
    }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69