Java如何使用正则表达式拆分字符串?
本示例使用该java.util.regex.Pattern.split()方法分割由逗号或空格分隔的输入字符串。
package org.nhooo.example.regex; import java.util.regex.Pattern; public class RegexSplitExample { public static void main(String[] args) { //查找逗号,空格(空格,制表符,换行, //回车,换页)。 String pattern = "[,\\s]+"; String colours = "Red,White, Blue Green Yellow, Orange"; Pattern splitter = Pattern.compile(pattern); String[] result = splitter.split(colours); for (String colour : result) { System.out.format("Colour = \"%s\"%n", colour); } } }
我们的代码片段的结果是:
Colour = "Red" Colour = "White" Colour = "Blue" Colour = "Green" Colour = "Yellow" Colour = "Orange"