Java如何拆分正则表达式和字符串?

在Java编程中,如何拆分正则表达式和字符串?

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

package com.yiibai;

import java.util.regex.Pattern; public class SplittingRegularExpression { 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]); } } } 
Java

上述代码示例将产生以下结果 -

this
is
the
Java
example
Shell

示例-2

以下是如何拆分正则表达式的另一个示例。

package com.yiibai;

import java.util.regex.Pattern; public class SplittingRegularExpression2 { 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("(to|Java|in|are|used)"); String[] parts = p1.split(s1); for (String p : parts) { System.out.println(p); } } } 
Java

上述代码示例将产生以下结果 -

Learn how 
 use regular expression 

 programm
g. Here 
 most commonly 
 example

转载于:https://www.cnblogs.com/borter/p/9617155.html

你可能感兴趣的:(Java如何拆分正则表达式和字符串?)