`

Java 正则表达式

 
阅读更多
package com.test.regex;

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

/**
 * 
 * String 关于正则表达式的三个方法 String.matches() String.split() String.replace()
 * 
 * @author, create on 2014-5-31 下午2:05:45
 * 
 */

public class Test {

	public void testMatches() {
		String str = "13516213428";
		boolean b = Pattern.matches("1[3-8]\\d{9}", str);
		System.out.println("phone:" + b);

		str = "labreeze@126.com";
		b = Pattern.matches("\\w{1,}@\\w{1,}(.com|.net|.cn|.org)", str);
		System.out.println("email:" + b);

		// 或者另一种写法 详见java源码
		// public static boolean matches(String regex, CharSequence input) {
		// Pattern p = Pattern.compile(regex);
		// Matcher m = p.matcher(input);
		// return m.matches();
		// }

		final Pattern pattern = Pattern
				.compile("\\w{1,}@\\w{1,}(.com|.net|.cn|.org)");
		final Matcher matcher = pattern.matcher("labreeze@126.com");
		b = matcher.matches();
		System.out.println("another:" + b);

	}

	/**
	 * result: this\n is\n my\n world
	 */
	public void testMatcher() {
		final Pattern pattern = Pattern.compile("\\w{1,}");
		final Matcher matcher = pattern.matcher("this  is   my world");
		while (matcher.find()) {
			System.out.println(matcher.group());
		}

		// 从指定位置开始查找正则表达式
		final int i = 5;
		if (matcher.find(i)) {
			System.out.println(matcher.group());
		}
	}

	public void testSplit() {
		final Pattern pattern = Pattern.compile("--");
		final String inputString = "hello--this--is--my--world";
		String[] strs = pattern.split(inputString);
		for (final String s : strs) {
			System.out.println(s);
		}

		// 限制分段
		strs = pattern.split(inputString, 2);
		for (final String s : strs) {
			System.out.println(s);
		}

	}

	/**
	 * 正则表达式之替换
	 */
	public void testReplace() {
		final Pattern pattern = Pattern.compile("正则表达式");
		final Matcher matcher = pattern
				.matcher("正则表达式 Hello World,正则表达式 Hello World"); // 替换第一个符合正则的数据
		System.out.println(matcher.replaceFirst("Java"));
		System.out.println(matcher.replaceAll("Java"));
	}

	public static void main(final String[] args) {
		final Test test = new Test();

		// test.testMatches();

		// test.testMatcher();

		// test.testSplit();

		test.testReplace();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics