Java 示例 - 拆分正则表达式
-
问题描述
如何拆分正则表达式? -
解决方案
以下示例演示如何使用 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]); } } }
-
结果
上面的代码示例将产生以下结果。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