Regex to match continuous pattern of integer then space

后端 未结 4 940
一生所求
一生所求 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:09

    To "parse out" the integers, you don't necessarily want to match the input, but rather you want to split it on spaces (which uses regex):

    String[] nums = input.trim().split("\\s+");
    

    If you actually want int values:

    List<Integer> selections = new ArrayList<>();
    for (String num : input.trim().split("\\s+"))
        selections.add(Integer.parseInt(num));
    
    0 讨论(0)
  • 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<String> result = new ArrayList<String>();
    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<result.size();i++) {
        System.out.println(result.get(i));
    }
    

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

    0 讨论(0)
  • 2021-01-22 02:27

    You want integers:

    \d+
    

    followed by any number of space, then another integer:

    \d+( \d+)*
    

    Note that if you want to use a regex in a Java string you need to escape every \ as \\.

    0 讨论(0)
  • 2021-01-22 02:32
    Pattern pattern = new Pattern(^([0-9]*\s+)*[0-9]*$)
    

    Explanation of the RegEx:

    • ^ : beginning of input
    • [0-9] : only digits
    • '*' : any number of digits
    • \s : a space
    • '+' : at least one space
    • '()*' : any number of this digit space combination
    • $: end of input

    This treats all of the following inputs as valid:

    • "1"
    • "123 22"
    • "123 23"
    • "123456 33 333 3333 "
    • "12321 44 452 23 "

    etc.

    0 讨论(0)
提交回复
热议问题