- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.IOException;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import java.util.regex.PatternSyntaxException;
- /**
- * 检查你输入的正则表达式是否正确。
- * 生成 : javac Regex.java
- * 运行 : java Regex
- * 操作 : 运行后直接进入交互模式,在"Please enter your pattern ... "行中输入Pattern,
- * 然后在"Please enter text to test ..."行中输入检查的文本。
- * 如果匹配显示"Match!", 否则显示"Unmatch"。
- * 输入"ok" 回退及结束。
- */
- public class Regex
- {
- public static final void main(String[] args)
- {
- BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
- String pStr = null;
- try
- {
- while(true)
- {
- System.out.print("Please enter your pattern (\\"ok\\" for done) : ");
- while(s.ready());
- pStr = s.readLine();
- if (pStr.equals("ok")) break;
- Pattern p = null;
- try
- {
- p = Pattern.compile(pStr);
- }
- catch (PatternSyntaxException e)
- {
- System.out.printf("Your pattern contains error : %s", e.getDescription());
- System.out.println();
- continue;
- }
- System.out.println("Pattern is correct");
- while (true)
- {
- System.out.print("Please enter text to test (\\"ok\\" for done) : ");
- while (s.ready());
- pStr = s.readLine();
- if (pStr.equals("ok")) break;
- Matcher m = p.matcher(pStr);
- if (m != null && m.matches())
- {
- System.out.println("Match!");
- }
- else
- {
- System.out.println("Unmatch!");
- }
- }
- }
- }
- catch (IOException e)
- {
- System.err.println("IO exception and quit");
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2212201514250.html
来源: http://www.codesnippet.cn/detail/2212201514250.html