如何拆分正则表达式?(How to split a regular expression?)

优质
小牛编辑
121浏览
2023-12-01

问题描述 (Problem Description)

如何拆分正则表达式?

解决方案 (Solution)

下面的示例演示如何使用regex.Pattern类的Pattern.compile()方法和patternname.split()方法拆分正则表达式。

import java.util.regex.Pattern;
public class PatternSplitExample {
   public static void main(String args[]) {
      Pattern p = Pattern.compile(" ");
      String tmp = "this is the Java example";
      String[] tokens = p.split(tmp);
      for (int i = 0; i < tokens.length; i++) {
         System.out.println(tokens[i]);
      }
   }
}

结果 (Result)

上面的代码示例将产生以下结果。

this
is
the
Java
example

以下是拆分正则表达式的示例。

import java.util.regex.Pattern;
public class Main {
   public static void main(String a[]) {
      String s1 = "Learn how to use regular expression in Java programming. Here are most commonly used example";
      Pattern p1 = Pattern.compile("(use|Java|are|use)");
      String[] parts = p1.split(s1);
      for(String p:parts) { 
         System.out.println(p);
      } 
   }
}

上面的代码示例将产生以下结果。

Learn how to 
 regular expression in 
 programming. Here 
 most commonly 
d example