使用模式组查找第一个单词

时间:2016-03-16 06:47:10

标签: java regex pattern-matching matcher

我在查找以下文件名中的第一个单词时遇到问题。

12345.pdf ,
12345 203 1525345.pdf ,
12345_xxx.pdf ,
12345-xxx.pdf ,
12345 203-1525345.pdf ,
Smith 12345 03012016.pdf ,
Smith 12345 03012016-1.pdf 

我正在使用模式({ln}\\w+?)[_\\s-](\\w+?_)?({dc}\\w+?).(\\w+)并获取密钥ln(value = matcher.group("ln"))的值。

请帮忙。

这是我的程序,每次我只需要将值ln作为第一个单词。

    String[] fileName ={"12345.pdf","12345 203    1525345.pdf","12345_xxx.pdf","12345-xxx.pdf","12345 203-1525345.pdf","Smith 12345 03012016.pdf","Smith 12345 03012016-1.pdf"};
    String pat =  "({ln}\\w+?)[_\\s-](\\w+?[_\\s-])?({dc}\\w+?).(\\w+)";
    Pattern fileNamePattern = new Pattern(pat);
    for(String fileName1 : fileName)
    {
    Matcher matcher = fileNamePattern.matcher(fileName1);
    String value = null;
    if (matcher.matches())
    {
        value = matcher.group("ln");
    }
    System.out.print(fileName1 +" : ");
    System.out.println(value);
    }

}

}

和值: -

12345.pdf : 12345
12345 203 1525345.pdf : 12345
12345_xxx.pdf :12345
12345-xxx.pdf : 12345 
12345 203-1525345.pdf : 12345
Smith 12345 03012016.pdf : smith
Smith 12345 03012016-1.pdf :smith

2 个答案:

答案 0 :(得分:1)

^[a-zA-Z0-9]+(?=\b|_)

您只需使用multiline模式即可。请参阅演示。

https://regex101.com/r/kZ2iZ8/1

答案 1 :(得分:0)

使用word boundaries^ anchor

^\b[\w\.\d\-]+\b

Demo