Regex to match continuous pattern of integer then space

后端 未结 4 946
一生所求
一生所求 2021-01-22 01:35

I\'m asking the user for input through the Scanner in Java, and now I want to parse out their selections using a regular expression. In essence, I show them an enu

4条回答
  •  佛祖请我去吃肉
    2021-01-22 02:24

    If you want to ensure that your string contains only numbers and spaces (with a variable number of spaces and trailing/leading spaces allowed) and extract number at the same time, you can use the \G anchor to find consecutive matches.

    String source = "1 3 5 8";
    
    List result = new ArrayList();
    Pattern p = Pattern.compile("\\G *(\\d++) *(?=[\\d ]*$)");
    Matcher m = p.matcher(source);
    
    while (m.find()) {
        result.add(m.group(1));
    }
    for (int i=0;i

    Note: at the begining of a global search, \G matches the start of the string.

提交回复
热议问题