专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Java正则表达式教程的学习

Java正则表达式教程的学习

更新时间:2021-04-27 12:37:07 来源:赢咖4 浏览851次

什么是正则表达式?

正则表达式定义了字符串的模式。正则表达式可以用来搜索、编辑或处理文本。正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。Java正则表达式和Perl的是最为相似的。

Java正则表达式的类在 java.util.regex 包中,包括三个:Pattern,Matcher 和 PatternSyntaxException。

Pattern对象是正则表达式的已编译版本。他没有任何公共构造器,我们通过传递一个正则表达式参数给公共静态方法 compile 来创建一个pattern对象。

Matcher是用来匹配输入字符串和创建的 pattern 对象的正则引擎对象。这个类没有任何公共构造器,我们用patten对象的matcher方法,使用输入字符串作为参数来获得一个Matcher对象。然后使用matches方法,通过返回的布尔值判断输入字符串是否与正则匹配。

如果正则表达式语法不正确将抛出PatternSyntaxException异常。

让我们在一个简单的例子里看看这些类是怎么用的吧

package com.journaldev.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExamples {
  public static void main(String[] args) {
    // using pattern with flags
    Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("ABcabdAb");
    // using Matcher find(), group(), start() and end() methods
    while (matcher.find()) {
      System.out.println("Found the text \"" + matcher.group()
          + "\" starting at " + matcher.start()
          + " index and ending at index " + matcher.end());
    }
    // using Pattern split() method
    pattern = Pattern.compile("\\W");
    String[] words = pattern.split("one@two#three:four$five");
    for (String s : words) {
      System.out.println("Split using Pattern.split(): " + s);
    }
    // using Matcher.replaceFirst() and replaceAll() methods
    pattern = Pattern.compile("1*2");
    matcher = pattern.matcher("11234512678");
    System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
    System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
  }
}

既然正则表达式总是和字符串有关, Java 1.4对String类进行了扩展,提供了一个matches方法来匹配pattern。在方法内部使用Pattern和Matcher类来处理这些东西,但显然这样减少了代码的行数。

Pattern类同样有matches方法,可以让正则和作为参数输入的字符串匹配,输出布尔值结果。

下述的代码可以将输入字符串和正则表达式进行匹配。

String str = "bbb";
System.out.println("Using String matches method: "+str.matches(".bb"));
System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));

所以如果你的需要仅仅是检查输入字符串是否和pattern匹配,你可以通过调用String的matches方法省下时间。只有当你需要操作输入字符串或者重用pattern的时候,你才需要使用Pattern和Matches类。

注意由正则定义的pattern是从左至右应用的,一旦一个原字符在一次匹配中使用过了,将不会再次使用。

以上就是赢咖4小编介绍的“Java正则表达式教程的学习”的内容,希望对大家有帮助,如有疑问,请在线咨询,有专业老师随时为您服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>