public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map map = new HashMap();
while (n != 0) {
while(sc.hasNext("\\d+"+" "+"\\d+")){
String[] string=sc.nextLine().split(" ");
map.put(new Integer(string[0]), new Integer(string[1]));
}
n--;
}
Set<Integer> set = map.keySet();
for (Integer it : set) {
int value = map.get(it);
System.out.println(it + " " + value);
}
}
}
我的目的是从键盘输入n个键值对,要求输入是键 空格 值,如1 15,然后,找出键值相同的元素,去重,重新按照之前格式输出,可是我的正则表达式为什么不匹配,写的不对吗,老是进不去while(sc.hasNext("\d+"+" "+"\d+"))循环体,只是为什么?
空白字符的正则表达式不是(" ")这样的。是\s(小s)
Scanner sc = new Scanner(System.in);
String regex = "^\\d+\\s+\\d+";
// "\\d+":表示一个或多个数字。
while (sc.hasNext()) {
String result = sc.nextLine();
if (result.matches(regex)) {
System.out.println(result + ":good");
//处理
} else {
System.out.println(result + ":bad");
}
}