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

本文介绍了一种在Java中使用正则表达式验证彩票中奖号码的方法,并提供了一个示例程序来展示如何进行字符串匹配及查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正则表达式在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");
			}
		}

	}

}
		

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值