正则表达式是用于文本搜索的非常重要的工具。 以下是用于执行正则表达式搜索并基于正则表达式捕获字符串的不同部分的代码段
public class RegexTest { public static void main(String[] args) { String name = "01_My-File.pdf" ; match(name); match( "09_03_12File.docx" ); match( "09_03_12File.q123" ); } public static void match(String input){ System.out.println( "********* Analysing " + input+ " *********" ); String regex = "([0-9]+)([_])(.*)([\\.])([A-Za-z]+)" ; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); if (!matcher.matches()){ System.out.println( "Input not matches regex" ); return ; } System.out.println( "Matches: " + matcher.matches()); String number = matcher.group(1); System.out.println( "Index: " + number); String fileName = matcher.group(3); System.out.println( "FileName: " + fileName); String extension = matcher.group(5); System.out.println( "Extension: " + extension); } }
使用()
捕获组。 在上面的正则表达式中([0-9]+)([_])(.*)([\.])([A-Za-z]+)
- 第一组定义为至少一个数字的数字
- 第二组是固定字符_
- 第三组是任何文本。
- 第四组是固定字符。 (我们必须使用\\进行转义
.
因为在正则表达式中,.
表示任何字符,符号,空格或数字)。 - 第五组是长度大于0的字符组。
我们使用Pattern
类来编译正则表达式,并使用它匹配输入以生成Matcher
实例。 此Matcher
具有有关正则表达式匹配结果的信息。
翻译自: https://www.javacodegeeks.com/2020/02/how-to-use-regular-expression-in-java.html