输入模式匹配java

时间:2011-04-22 18:56:52

标签: java regex

我想编写一个函数validate(),它将一些模式或正则表达式作为参数,并要求用户输入它的选择。如果选择与模式匹配,则返回选择,否则将要求用户重新输入选择。

例如,如果我以validate()作为参数调用123,它将返回123,具体取决于用户输入。

但我不知道如何使用模式或正则表达式。请帮忙。

我已经编写了一些代码,但我不确定在几个地方写什么。 我希望下面写的验证函数接受输入1或2或3并返回相同的内容。

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Pat
{
  public static void main(String args[])
  {
    int num=validate(Pattern.compile("123"));//I don't know whether this is right or not
    System.out.println(num);
  }
  static int validate(Pattern pattern)
  {
    int input;
    boolean validInput=false;
    do
    {
      try
      {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        input=Integer.parseInt(br.readLine());
        validInput=true;
      }catch(Exception e)
      {
        System.out.println(""+e);
      }
    }while(!validInput || input.matches(pattern));// This also seems like a problem.
    return input;
  }
}

2 个答案:

答案 0 :(得分:2)

我认为您打算将您的模式输入为“[123]”。

你几乎自己解决了这个问题。 :)

另外我注意到你应该重新考虑的事情。这是我编辑后的代码。享受,希望它做你想要的。

import java.io.*;


class Pat
{
    public static void main(String args[])
    {
        int num = validate("[123]");
        System.out.println(num);
    }

    static int validate(String pattern)
    {
        String input = "";
        boolean validInput = false;
        do
        {
            try
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                input = br.readLine();
                if(input.matches(pattern))
                    validInput = true;
            }catch(Exception e)
            {
                System.out.println("" + e);
            }
        }while(!validInput);
        return Integer.parseInt(input);
    }
}

Oi,Boro。

答案 1 :(得分:0)

如果您不想使用模式匹配器,您只需检查输入是否是您的选项字符串中的一个字符。

public class Main {
public static void main(String[] args) {
    String options = "123abc";
    System.out.println("You chose option: " + validate(options));
}

static String validate(String options)
{
    boolean validInput=false;
    String input = "";
    do {
        System.out.println("Enter one of the following: " + options);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        try {
            input = br.readLine();
            if (input.length() == 1 && options.indexOf(input) >= 0) {
              validInput=true;
            }
        } catch (IOException ex) {
            // bad input
        }
    } while(!validInput);
    return input;
} }
相关问题