正则表达式在Java代码中的使用

正则表达式在Java代码中的使用:

 

 

中奖号码录入功能中,对于中奖号码的录入的验证:

	/**
	 * 使用正则验证开奖号码(有参)
	 * 
	 * @param pattern
	 *            正则表达式
	 * @param content
	 *            内容
	 * @author hl
	 */
	public void checkNumbers(String pattern, String content, Integer lottTypeId)
			throws Exception {
		// TODO Auto-generated method stub
		Pattern rule = Pattern.compile(pattern);
		Matcher matcher = rule.matcher(content);
		boolean found = false;
		while (matcher.find()) {
			if (lottTypeId == 7 && content.length() == 3) {
				found = true; // 3D
			} else if (lottTypeId == 9 && content.length() == 14) {
				found = true; // 双色球
			} else if (lottTypeId == 10 && content.length() == 16) {
				found = true; // 七乐彩
			} else if (lottTypeId == 11 && content.length() == 10) {
				found = true; // 22选 5
			}
		}
		if (!found) {
			throw new Exception("开奖号码格式错误!");
		}
	}

 

 

实例列举:

package com.ccw.actions;

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

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.printf("%nEnter your regex: ");
			Pattern pattern = Pattern.compile(scanner.nextLine());
			System.out.printf("Enter input string to search: ");
			Matcher matcher = pattern.matcher(scanner.nextLine());
			boolean found = false;
			while (matcher.find()) {
				System.out
						.printf(
								"I found the text \"%s\" starting at index %d and ending at index %d.%n",
								matcher.group(), matcher.start(), matcher.end());
				found = true;
			}
			if (!found) {
				System.out.printf("No match found.%n");
			}
		}

	}

}
		

 

 

 

你可能感兴趣的:(java,正则表达式)