439. Java 正则表达式 - 字符串字面量与元字符

发布时间:2026/6/19 12:02:11
439. Java 正则表达式 - 字符串字面量与元字符 文章目录439. Java 正则表达式 - 字符串字面量与元字符1. 字符串字面量匹配String Literals 示例 连续匹配的例子2. 元字符Metacharacters 示例.点号Java 正则里的元字符列表3. 如何匹配“普通的元字符”4. 小结 ✅QA439. Java 正则表达式 - 字符串字面量与元字符1. 字符串字面量匹配String Literals正则表达式最基础的功能就是匹配一个固定的字符串。 如果正则表达式是foo输入字符串也是foo匹配就会成功。 示例publicstaticvoidmain(String[]args){java.util.Scannerscannernewjava.util.Scanner(System.in);System.out.println(\n 正则表达式交互式测试 );System.out.println(提示: 输入 quit 退出程序\n);while(true){System.out.print(Enter your regex: );StringregexInputscanner.nextLine();if(quit.equalsIgnoreCase(regexInput)){System.out.println(程序已退出);break;}try{PatternuserPatternPattern.compile(regexInput);System.out.print(Enter input string to search: );StringinputStringscanner.nextLine();MatcheruserMatcheruserPattern.matcher(inputString);booleanfoundfalse;while(userMatcher.find()){foundtrue;System.out.printf(I found the text \%s\ starting at index %d and ending at index %d.%n,userMatcher.group(),userMatcher.start(),userMatcher.end());}if(!found){System.out.println(No match found.);}}catch(Exceptione){System.out.println(正则表达式错误: e.getMessage());}System.out.println();// 空行分隔}scanner.close();}Enteryour regex:fooEnterinput stringtosearch:fooIfound the text foo starting at index0and ending at index3.这里有几个细节输入foo长度是 3但结果显示start index 0end index 3为什么因为正则里的索引范围是起始索引 inclusive包含结束索引 exclusive不包含 用一个图来帮助理解String:f o oIndex:0123foo实际占用的是 0, 1, 2 三个单元格但结束索引指向 3相当于最后一个字符的“后面” 连续匹配的例子Enteryour regex:fooEnterinput stringtosearch:foofoofooIfound the text foo starting at index0and ending at index3.Ifound the text foo starting at index3and ending at index6.Ifound the text foo starting at index6and ending at index9. 可以看到下一个匹配的开始位置就是上一个匹配的结束位置。这就是正则引擎的匹配机制。2. 元字符Metacharacters正则表达式并不仅仅是匹配固定字符串它有一组特殊字符metacharacters能让匹配变得更灵活。 示例.点号如果正则表达式是cat.输入字符串是cats结果如下Enteryour regex:cat.Enterinput stringtosearch:catsIfound the text cats starting at index0and ending at index4. 注意虽然输入中没有写.但匹配依然成功。原因是.是一个元字符表示任意单个字符。所以cat.可以匹配catscatacat!cat?等等。Java 正则里的元字符列表([{\^-$!|]})?*.这些符号在正则表达式里都有特殊含义。 但注意像、#这样的符号永远没有特殊含义始终是普通字符。3. 如何匹配“普通的元字符”有时我们并不想让.当作“任意字符”而是就想匹配一个真正的点号.。 这时有两种方式用反斜杠\转义PatternpPattern.compile(cat\\.);Matchermp.matcher(This is a cat.);System.out.println(m.find());// truecat\\.表示匹配字面量字符串 “cat.”之所以要写两个\\是因为在 Java 字符串里\也需要转义。用\Q...\E引用区块PatternpPattern.compile(\\Qcat.\\E);Matchermp.matcher(This is a cat.);System.out.println(m.find());// true\Q开始转义直到\E结束。中间的所有字符都会被当作普通字符。所以\\Qcat.\\E等价于cat\\.。4. 小结 ✅字符串字面量正则foo匹配输入foo索引规则开始索引包含结束索引不包含元字符.表示任意单字符转义方法用\\转义常见方式用\Q...\E包裹QA让学员尝试写出一个能匹配112的正则需要转义和提问.*能匹配什么内容提问foo.和foo\\.有什么区别