Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    /**
     * Get all the matches for {@code string} compiled by {@code pattern}. If 
     * {@code isGlobal} is true, the return results will only include the 
     * group 0 matches. It is similar to string.match(regexp) in JavaScript.
     * 
     * @param pattern the regexp
     * @param string the string
     * @param isGlobal similar to JavaScript /g flag
     * 
     * @return all matches
     */
    public static String[] match(Pattern pattern, String string, boolean isGlobal) {
        if (pattern == null) {
            throw new NullPointerException("argument 'pattern' cannot be null");
        }
        if (string == null) {
            throw new NullPointerException("argument 'string' cannot be null");
        }

        List<String> matchesList = new ArrayList<String>();

        Matcher matcher = pattern.matcher(string);
        while (matcher.find()) {
            matchesList.add(matcher.group(0));
            if (!isGlobal) {
                for (int i = 1, iEnd = matcher.groupCount(); i <= iEnd; i++) {
                    matchesList.add(matcher.group(i));
                }
            }
        }

        return matchesList.toArray(new String[matchesList.size()]);
    }
}