从包含文件名的字符串中提取模式

时间:2019-08-30 20:38:50

标签: java pattern-matching

我想从字符串下面提取uid后缀。我正在尝试模式。但是找不到匹配项。

输入:exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt

uid :29510309-5673-4c20-83bd-6d2303c21016

后缀:0

public class Test {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("exportDocumentInfo_*-*.txt");
        String mydata = "exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt
";

        Matcher matcher = pattern.matcher(mydata);
        if(matcher.matches()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
        }

    }

3 个答案:

答案 0 :(得分:1)

将每个*替换为(.*)。另外,请删除";之前的换行符,否则,该程序将无法编译。结果应类似于以下内容:

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

public class Test {
    public static void main(final String[] args) {
        final Pattern pattern = 
                Pattern.compile("exportDocumentInfo_(.*)-(.*).txt");
        final String mydata =
                "exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt";
        final Matcher matcher = pattern.matcher(mydata);

        if (matcher.matches()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
        }
    }
}

Ideone example

答案 1 :(得分:1)

您需要使用exportDocumentInfo_([\w-]+)-([0-9]+)\.txt之类的模式,要使用组,需要带括号来捕获内容,并且只允许最后一组中的数字

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("exportDocumentInfo_([\w-]+)-([0-9]+)\.txt");
    String mydata = "exportDocumentInfo_29510309-5673-4c20-83bd-6d2303c21016-0.txt";
    Matcher matcher = pattern.matcher(mydata);

    if (matcher.matches()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }

}

>> Regex demo

答案 2 :(得分:1)

这是另一个解决该问题的正则表达式(只需将其替换为您的代码即可):

exportDocumentInfo_(.*)-(.*).txt

https://css-tricks.com/snippets/css/a-guide-to-flexbox/