Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

public class Main {
    private static Pattern range0Pattern = Pattern.compile("(\\D)(\\d+?)-(\\d+?)");

    public static String[] range(String in) {
        // basic form: x1, x2, x3, x4
        // range form: x1-5, n3-7
        List<String> rs = new ArrayList<String>();

        for (String s : Splitter.on(",").trimResults().omitEmptyStrings().split(in)) {
            s = s.trim();
            if (range0(rs, s))
                continue;

            rs.add(s);
        }

        Collections.sort(rs);
        return Iterables.toArray(rs, String.class);
    }

    /**
     * Handle range form like x3-12
     *
     * @param rs Range List
     * @param r Range Token
     */
    private static boolean range0(List<String> rs, String r) {
        Matcher matcher = range0Pattern.matcher(r);
        if (!matcher.matches())
            return false;

        String prefix = matcher.group(1);
        int begin = Integer.parseInt(matcher.group(2));
        int end = Integer.parseInt(matcher.group(3));
        for (int i = begin; i <= end; ++i) {
            rs.add(prefix + i);
        }
        return true;
    }
}