输入模式匹配java
我想写一个函数validate()
它将采取一些模式或正则表达式作为参数,并会要求用户输入它的选择。如果选择符合模式,它将返回选择,否则它会要求用户重新输入选择。输入模式匹配java
例如,如果我打电话validate()
与123
作为参数,它将返回要么1
或2
或3
取决于用户输入。
但我不知道如何使用模式或正则表达式。请帮忙。
我写了一些代码,但我不知道在几个地方写什么。 我想要下面写的验证函数接受输入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;
}
}
我想你的意思是输入你的模式为“[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。
非常感谢!它的作品完美! – 2011-04-22 20:45:05
@powerpravin快乐我的所有:)我希望你了解所有的变化,为什么我做了他们。在[Java RegEx教程预定义字符类](http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html)中,您可以找到很多信息,这些信息可以帮助您更好地理解解决方案。 – Boro 2011-04-23 05:29:35
如果您不想使用模式匹配器,则可以检查输入是否为选项字符串中的一个字符。
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;
} }
感谢您的回复。但我希望这种方法能够进行概括并使其不仅能接受单个字符,还能接受字符串。 – 2011-04-23 19:11:32
您是否阅读过文档? – Oded 2011-04-22 18:58:18
http://www.regular-expressions.info/java.html - 良好的指导 – nsfyn55 2011-04-22 18:59:27
我已阅读它。但我不知道如何实施它。 – 2011-04-22 19:01:32