输入模式匹配java
我想编写一个函数输入模式匹配java,java,regex,Java,Regex,我想编写一个函数validate(),它将以一些模式或正则表达式作为参数,并要求用户输入其选择。如果选择与模式匹配,它将返回选择,否则它将要求用户重新输入选择 例如,如果我使用123作为参数调用validate(),它将根据用户输入返回1或2或3 但我不知道模式或正则表达式是如何使用的。请帮忙 我已经写了一些代码,但我不确定在几个地方写什么。 我希望下面编写的validate函数接受输入1、2或3并返回相同的值 import java.io.*; import java.util.regex.M
validate()
,它将以一些模式或正则表达式作为参数,并要求用户输入其选择。如果选择与模式匹配,它将返回选择,否则它将要求用户重新输入选择
例如,如果我使用123
作为参数调用validate()
,它将根据用户输入返回1
或2
或3
但我不知道模式或正则表达式是如何使用的。请帮忙
我已经写了一些代码,但我不确定在几个地方写什么。
我希望下面编写的validate函数接受输入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.如果不想使用模式匹配器,只需检查输入是否是选项字符串中的字符之一
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;
} }
你看过文件了吗很好,我读过了。但我不知道如何实现它。你为什么不写一些代码,看看你能走多远?然后,如果您陷入困境,发布您所拥有的内容并提出一个特定的问题。@Isaac:我已经编辑了问题并添加了代码。@powerpravin:我所有的:)我希望您理解所有的更改以及我做出更改的原因。在中,您可以找到许多信息,这些信息将帮助您更好地理解解决方案。感谢您的回复。但是我想让这个方法进行泛化,使它不仅能接受单个字符,还能接受字符串。