String 分割(备忘)

简述:

常用String 分割


1. Scanner

package com.anialy.string;

import java.util.Scanner;

public class Test1 {
	public static void main(String[] args) {
		Scanner scan = new Scanner("hello world !");
		scan.useDelimiter(" ");
		while(scan.hasNext()){
			System.out.println(scan.next());
		}
	}
}

输出:




2. 正则表达式划分

package com.anialy.string;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test2 {
	public static void main(String[] args) {
		String str = "{1:hello} {2:world} {3:!}";
		Pattern pattern = Pattern.compile("[{]([0-9]+):(.*?)[}]");  
        Matcher matcher = pattern.matcher(str);
        while(matcher.find()){  
        	String key = matcher.group(1);
        	String value = matcher.group(2);
        	System.out.println(key + ": " + value);
        }
	}
}


输出:





你可能感兴趣的:(String 分割(备忘))