RegEx用于匹配特定的Excel路径

时间:2019-06-21 06:32:56

标签: java regex

我正在创建一个正则表达式以支持以下模式

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

尝试

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

此正则表达式匹配所有必需的模式,但是我怎么能限制到最后一个字符。

1 个答案:

答案 0 :(得分:-1)

我的猜测是,您可能想要一个类似于以下内容的表达式:

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

或:

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

enter image description here

Demo 1

测试

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电路

Demo 2可视化正则表达式:

jex.im