简体   繁体   English

使用 Java 模式提取四位数字的正则表达式

[英]Regex to extract four digits using Java Pattern

I'm trying to extract four digits before the file extension using Java Pattern Matchers.我正在尝试使用 Java 模式匹配器在文件扩展名之前提取四位数字。 It's throwing no group found exception.它没有抛出任何组发现异常。 Can someone help me on this?有人可以帮我吗?

String fileName = "20210101-000000_first_second_1234.csv";
Pattern pattern = Pattern.compile("\\\\d{4}");
System.out.println(pattern.matcher(fileName).group(4));

I would like to get 1234 from the fileName.我想从文件名中得到1234 I compiled the file pattern using regex \\\\d{4} .我使用正则表达式\\\\d{4}编译了文件模式。 Which returns four groups.返回四个组。 So, fourth group should suppose to return 1234 which is not returning, instead throwing group not found exception.因此,第四组应该假设返回未返回的1234 ,而不是抛出未找到组的异常。

The "\\\\d{4}" string literal defines a \\d{4} regex that matches a \dddd string (a backslash and then four d chars). "\\\\d{4}"字符串字面量定义了一个匹配\dddd字符串(反斜杠和四个d字符)的\\d{4}正则表达式。 You try to access Group 4, but there is no capturing group defined in your regex.您尝试访问第 4 组,但您的正则表达式中没有定义捕获组。 Besides, you can't access match groups before actually running the matcher with Matcher#find or Matcher#matches .此外,在使用Matcher#findMatcher#matches实际运行匹配器之前,您无法访问匹配组。

You can use您可以使用

String fileName = "20210101-000000_first_second_1234.csv";
Pattern pattern = Pattern.compile("\\d{4}(?=\\.[^.]+$)");
Matcher m = pattern.matcher(fileName);
if (m.find()) {
    System.out.println(m.group());
}

See the Java demo and the regex demo .请参阅Java 演示正则表达式演示 Details :详情

  • \d{4} - four digits \d{4} - 四位数字
  • (?=\.[^.]+$) - a positive lookahead that requires a . (?=\.[^.]+$) - 需要. char and then one or more chars other than . char 然后是一个或多个除. till end of string.直到字符串结束。

Note also the Matcher m = pattern.matcher(fileName) added and if (m.find()) checks if there is a match.还要注意Matcher m = pattern.matcher(fileName)添加和if (m.find())检查是否有匹配。 Only if there is a match, the value can be retrieved from the 0th group, m.group() .只有匹配时,才能从第 0 个组m.group()中检索该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM