【发布时间】:2018-09-25 07:27:14
【问题描述】:
如何检查用户是否以特定模式输入字符串。我希望用户输入一个数字,然后输入一个逗号,然后再输入一个数字。例如,3,3 或 4,4。如果用户输入例如:3,,3,则不应被接受。
【问题讨论】:
-
请选择一个已接受的答案
标签: java regex string java.util.scanner
如何检查用户是否以特定模式输入字符串。我希望用户输入一个数字,然后输入一个逗号,然后再输入一个数字。例如,3,3 或 4,4。如果用户输入例如:3,,3,则不应被接受。
【问题讨论】:
标签: java regex string java.util.scanner
使用正则表达式\d+匹配号码组:
String input = "3,3";
System.out.println(input.matches("\\d+,\\d+")); // should be true
更新:
如果允许两个以上的数字,请使用(\\d+,)+\\d+ 匹配多个组。
【讨论】:
\d,\d。输入也可以是\d,\d,\d。
首先,看看RegExr 并在那里尝试一些东西。
对于您的问题,请使用下一个模式:\d+,\d+
【讨论】:
既然标有Scanner的问题我假设你想用它,所以你可以这样做
Scanner sc = new Scanner(System.in);
if (sc.hasNext("\\d+,\\d+")) {
// code for good case
} else {
// not matched
}
希望对你有帮助!
【讨论】:
尝试以下方法:
public class Demo3 extends AppCompatActivity {
private EditText edt;
private Button b;
private TextView tv;
private String days;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo3);
edt = (EditText) findViewById(R.id.edt);
tv = (TextView) findViewById(R.id.tv);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!edt.getText().toString().isEmpty()) {
String[] split_space = edt.getText().toString().split(",");// TODO: Check if input is actually an Integer , Integer.
if (split_space.length == 2) {
if(isValidInteger(split_space[0]) && isValidInteger(split_space[1])){
tv.setText("accepted");
}else{
tv.setText("not accepted (contains characters)");
}
} else {
tv.setText("not accepted (doesn't respect format (3,3 or 4,4 or ...))");
}
}else {
tv.setText("not accepted (empty)");
}
}
});
}
private boolean isValidInteger(String value) {
if (value == null) {
return false;
} else {
try {
Integer val = Integer.valueOf(value);
if (val != null)
return true;
else
return false;
} catch (NumberFormatException e) {
return false;
}
}
}
}
demo3.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="null"
android:id="@+id/tv"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check"
android:layout_marginTop="50dp"
android:id="@+id/b"/>
</LinearLayout>
【讨论】:
Scanner scan = new Scanner(System.in);
String str= null;
if(scan.hasNext("\\d+,\\d+")){
str = scan.next();
}
if(str != null){
System.out.println("Valid User Input: {"+str+"} Recieved");
}
else{
System.out.println("Invalid User Input");
}
如果模式不匹配,str 将等于 null
【讨论】: