正则式的使用

 1 import java.util.Scanner;
2
3 public class RegDemo {
4
5 /**
6 * @param args
7 * 1 对于坐标输入数据的匹配和解析 坐标的形式为"5,f"或"5 f"完成RegDemo的read方法 输入:2,3
8 * 输出:i:2,j:3 输入:2 3 输出:i:2,j:3 正则表达式为:^\d+(,\s?|\s+)?\d+$
9 */
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12 String s=read("请输入一个坐标:");
13 System.out.println(s);
14 }
15
16 public static String read(String message) {
17 Scanner console = new Scanner(System.in);
18 while (true) {
19 System.out.println(message);
20 String str = console.nextLine();
21 String reg = "^\\d+(,\\s?|\\s+)?\\d+$";
22 boolean b = str.matches(reg);
23 if (b) {
24 String[] data = str.split(",\\s?|\\s+");
25 int x = Integer.parseInt(data[0]);
26 int y = Integer.parseInt(data[1]);
27 System.out.print("输出为:");
28 return "i" + ":" + x + "," + "j" + ":" + y;
29 }else
30 continue;
31 }
32 }
33 }

原文地址:https://www.cnblogs.com/superjt/p/2117910.html