【问题标题】:Find the first word using pattern group使用模式组查找第一个单词
【发布时间】:2016-03-16 06:47:09
【问题描述】:

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

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

【问题讨论】:

  • 你得到的输出是什么,预期的输出是什么?
  • 请看我的程序..我想要键 ln 的值作为第一个单词..

标签: java regex pattern-matching matcher


【解决方案1】:
^[a-zA-Z0-9]+(?=\b|_)

您可以简单地将其与multiline 模式一起使用。参见演示。

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

【讨论】:

    【解决方案2】:

    使用word boundaries^ anchor

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

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2020-09-17
      • 2013-04-08
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多