hdu1039 java正则表达式解法

Easier Done Than Said?

题意就是测试一段字符串是否满足下面三个条件:

(1)至少含有一个元音(a、e、i、o、u)

(2)不能连续三个是元音,也不能连续三个是非元音

(3)不能有连续两个字母是相同的,但是ee和oo除外

默认情况下,给出的字符串只含有小写字母。

当然这道题目用c++,解起来也不是很困难的,这次用java主要是练习正则表达式。

java代码是:

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

public class Main {
	public static void main(String[] args) throws Exception {
		Scanner cin = new Scanner(System.in);
		while (cin.hasNext()) {
			String str = cin.next();
			if(str.equals("end"))
				break;
			Pattern p1 = Pattern.compile("[aeiou]{3}|[^aeiou]{3}");
			Pattern p2 = Pattern.compile("([^eo])\1");
			Pattern p3 = Pattern.compile("[aeiou]+");
			Matcher m = p1.matcher(str);
			boolean flag = false;
			if(!m.find())
			{
				m = p2.matcher(str);
				if(!m.find())
				{
					m = p3.matcher(str);
					if(m.find())
						flag = true;
				}
			}
			if(flag)
				System.out.println("<"+str+"> is acceptable.");
			else
				System.out.println("<"+str+"> is not acceptable.");
		}
		cin.close();
	}
}

关于正则式:

[aeiou]{3}|[^aeiou]{3}  三个连续元音,或者三个连续非元音

 ([^eo])\1在字符串中   要进行转义所以要写  \  来代表   意思是两个连续元音除(ee,oo)。这个写法([a-df-np-z])\1  比较丑,呵呵.

                            ()表示分组,和1连用。1表示对前面第一个匹配到的组的一个引用,也就是 相同的效果。比如(a)1和(a)(a)同样意思。

[aeiou]+ 匹配至少有一个元音。+是一个或多个,*是0个或多个,?是0个或1个


 

原文地址:https://www.cnblogs.com/unclejelly/p/4082103.html