Example usage for java.lang String regionMatches

List of usage examples for java.lang String regionMatches

Introduction

In this page you can find the example usage for java.lang String regionMatches.

Prototype

public boolean regionMatches(int toffset, String other, int ooffset, int len) 

Source Link

Document

Tests if two string regions are equal.

Usage

From source file:org.apache.sysml.runtime.io.IOUtilFunctions.java

public static String[] splitCSV(String str, String delim, String[] tokens) {
    // check for empty input
    if (str == null || str.isEmpty())
        return new String[] { "" };

    // scan string and create individual tokens
    int from = 0, to = 0;
    int len = str.length();
    int pos = 0;/* w w  w .  j a  v  a 2  s  .  c om*/
    while (from < len) { // for all tokens
        if (str.charAt(from) == CSV_QUOTE_CHAR && str.indexOf(CSV_QUOTE_CHAR, from + 1) > 0) {
            to = str.indexOf(CSV_QUOTE_CHAR, from + 1);
            // handle escaped inner quotes, e.g. "aa""a"
            while (to + 1 < len && str.charAt(to + 1) == CSV_QUOTE_CHAR)
                to = str.indexOf(CSV_QUOTE_CHAR, to + 2); // to + ""
            to += 1; // last "
        } else if (str.regionMatches(from, delim, 0, delim.length())) {
            to = from; // empty string
        } else { // default: unquoted non-empty
            to = str.indexOf(delim, from + 1);
        }

        // slice out token and advance position
        to = (to >= 0) ? to : len;
        tokens[pos++] = str.substring(from, to);
        from = to + delim.length();
    }

    // handle empty string at end
    if (from == len)
        tokens[pos] = "";

    // return tokens
    return tokens;
}

From source file:org.apache.sysml.runtime.io.IOUtilFunctions.java

/**
 * Splits a string by a specified delimiter into all tokens, including empty
 * while respecting the rules for quotes and escapes defined in RFC4180.
 * /*  w  w  w. j av  a 2  s.  c  om*/
 * NOTE: use StringEscapeUtils.unescapeCsv(tmp) if needed afterwards.
 * 
 * @param str string to split
 * @param delim delimiter
 * @return string array
 */
public static String[] splitCSV(String str, String delim) {
    // check for empty input
    if (str == null || str.isEmpty())
        return new String[] { "" };

    // scan string and create individual tokens
    ArrayList<String> tokens = new ArrayList<String>();
    int from = 0, to = 0;
    int len = str.length();
    while (from < len) { // for all tokens
        if (str.charAt(from) == CSV_QUOTE_CHAR && str.indexOf(CSV_QUOTE_CHAR, from + 1) > 0) {
            to = str.indexOf(CSV_QUOTE_CHAR, from + 1);
            // handle escaped inner quotes, e.g. "aa""a"
            while (to + 1 < len && str.charAt(to + 1) == CSV_QUOTE_CHAR)
                to = str.indexOf(CSV_QUOTE_CHAR, to + 2); // to + ""
            to += 1; // last "
        } else if (str.regionMatches(from, delim, 0, delim.length())) {
            to = from; // empty string
        } else { // default: unquoted non-empty
            to = str.indexOf(delim, from + 1);
        }

        // slice out token and advance position
        to = (to >= 0) ? to : len;
        tokens.add(str.substring(from, to));
        from = to + delim.length();
    }

    // handle empty string at end
    if (from == len)
        tokens.add("");

    // return tokens
    return tokens.toArray(new String[0]);
}

From source file:org.omegat.util.FileUtil.java

static Pattern compileFileMask(String mask) {
    StringBuilder m = new StringBuilder();
    // "Relative" masks can match at any directory level
    if (!mask.startsWith("/")) {
        mask = "**/" + mask;
    }/*from   w w w .  ja va 2 s .c o  m*/
    // Masks ending with a slash match everything in subtree
    if (mask.endsWith("/")) {
        mask += "**";
    }
    for (int cp, i = 0; i < mask.length(); i += Character.charCount(cp)) {
        cp = mask.codePointAt(i);
        if (cp >= 'A' && cp <= 'Z') {
            m.appendCodePoint(cp);
        } else if (cp >= 'a' && cp <= 'z') {
            m.appendCodePoint(cp);
        } else if (cp >= '0' && cp <= '9') {
            m.appendCodePoint(cp);
        } else if (cp == '/') {
            if (mask.regionMatches(i, "/**/", 0, 4)) {
                // The sequence /**/ matches *zero* or more levels
                m.append("(?:/|/.*/)");
                i += 3;
            } else if (mask.regionMatches(i, "/**", 0, 3)) {
                // The sequence /** matches *zero* or more levels
                m.append("(?:|/.*)");
                i += 2;
            } else {
                m.appendCodePoint(cp);
            }
        } else if (cp == '?') {
            // ? matches anything but a directory separator
            m.append("[^/]");
        } else if (cp == '*') {
            if (mask.regionMatches(i, "**/", 0, 3)) {
                // The sequence **/ matches *zero* or more levels
                m.append("(?:|.*/)");
                i += 2;
            } else if (mask.regionMatches(i, "**", 0, 2)) {
                // **
                m.append(".*");
                i++;
            } else {
                // *
                m.append("[^/]*");
            }
        } else {
            m.append('\\').appendCodePoint(cp);
        }
    }
    return Pattern.compile(m.toString());
}

From source file:net.sf.xfd.provider.ProviderBase.java

@SuppressWarnings("SimplifiableIfStatement")
public static boolean mimeTypeMatches(String filter, String test) {
    if (test == null) {
        return false;
    } else if (filter == null || "*/*".equals(filter)) {
        return true;
    } else if (filter.equals(test)) {
        return true;
    } else if (filter.endsWith("/*")) {
        return filter.regionMatches(0, test, 0, filter.indexOf('/'));
    } else {/*from  w ww .  j a va2s .  co  m*/
        return false;
    }
}

From source file:sawtooth.examples.xo.XoHandler.java

/**
 * Helper function to retrieve the correct game info from the list of game data CSV.
 *///w w w . ja va 2  s  . com
private String getGameCsv(String stateEntry, String gameName) {
    ArrayList<String> gameCsvList = new ArrayList<>(Arrays.asList(stateEntry.split("\\|")));
    for (String gameCsv : gameCsvList) {
        if (gameCsv.regionMatches(0, gameName, 0, gameName.length())) {
            return gameCsv;
        }
    }
    return "";
}

From source file:ca.myewb.frame.PostParamWrapper.java

public void saveFile(String fieldPrefix, String subpath) throws Exception {

    for (String fileName : fileParams.keySet()) {
        log.info("Attempting to upload file from field: " + fileName);
        //subpath must be of form a/b/c not /a/b/c/
        if (fileParams.get(fileName) != null
                && fileName.regionMatches(0, fieldPrefix, 0, fieldPrefix.length())) {
            String[] dirs = subpath.split("/");
            String current = "";

            for (int i = 0; i < dirs.length; i++) {
                File currentSubDir = (new File(Helpers.getUserFilesDir() + current + "/" + dirs[i]));

                if (!currentSubDir.exists()) {
                    currentSubDir.mkdir();
                    log.info("Directory " + currentSubDir.getPath() + " created.");
                }//from  www.j  av  a2  s. com

                current += ("/" + dirs[i]);
            }

            DefaultFileItem item = ((DefaultFileItem) fileParams.get(fileName));
            String prepath = Helpers.getUserFilesDir() + "/" + subpath + "/";

            safeFileReplace(new File(prepath + makeNormalFileName(item.getName())), item);

            log.info("Successfully uploaded " + item.getName());
            Helpers.currentDailyStats().logFilesAdded();
        }
    }
}

From source file:org.apache.sling.servlets.resolver.internal.helper.ResourceCollector.java

private boolean matches(final String scriptName, final String name, String suffix) {
    if (suffix == null) {
        return scriptName.equals(name);
    }/* w w  w  .  j a v a  2  s  .  co m*/
    final int lenScriptName = scriptName.length();
    final int lenName = name.length();
    final int lenSuffix = suffix.length();
    return scriptName.regionMatches(0, name, 0, lenName)
            && scriptName.regionMatches(lenName, suffix, 0, lenSuffix)
            && lenScriptName == (lenName + lenSuffix);
}

From source file:org.wikipedia.nirvana.archive.ArchiveWithHeadersWithItemsCount.java

private void initPattern(String headerFormat) {
    ArrayList<HeaderFormatItem> pattern = new ArrayList<HeaderFormatItem>();
    int first = 0;
    //int index = 0;
    boolean wasPeriod = false;
    int pos = 0;/*from   w  w  w  .ja v a  2s  .  co  m*/
    while (pos < headerFormat.length()) {
        wasPeriod = false;
        for (Period p : Period.values()) {
            if (p == Period.NONE)
                continue;
            String param = p.template();
            if (headerFormat.regionMatches(pos, param, 0, param.length())) {
                if (first < pos) {
                    pattern.add(new HeaderFormatItem(headerFormat.substring(first, pos)));
                }
                pattern.add(new HeaderFormatItem(p));
                pos += param.length();
                first = pos;
                wasPeriod = true;
            }

        }
        if (headerFormat.regionMatches(pos, template, 0, template.length())) {
            if (first < pos) {
                pattern.add(new HeaderFormatItem(headerFormat.substring(first, pos)));
            }
            pattern.add(new HeaderFormatItem(template));
            pos += template.length();
            first = pos;
            wasPeriod = true;
        }
        //if(first!=pos || pos==0) pos++;
        if (!wasPeriod)
            pos++;

    }
    if (first < pos) {
        pattern.add(new HeaderFormatItem(headerFormat.substring(first, pos)));
    }
    this.patternOfHeader = pattern.toArray(new HeaderFormatItem[0]);
}

From source file:com.blackbear.flatworm.Record.java

/**
 * // w w w.  ja va2  s  . c o  m
 * @param String
 *          line of input from the file
 * @param FileFormat
 *          not used at this time, for later expansion?
 * @return boolean does this line match according to the defined criteria?
 */
public boolean matchesLine(String line, FileFormat ff) {
    switch (identTypeFlag) {

    // Recognition by value in a certain field
    // TODO: Will this work for delimited lines?
    case 'F':
        if (line.length() < fieldIdentStart + fieldIdentLength) {
            return false;
        } else {
            for (int i = 0; i < fieldIdentMatchStrings.size(); i++) {
                String s = (String) fieldIdentMatchStrings.get(i);
                if (line.regionMatches(fieldIdentStart, s, 0, fieldIdentLength)) {
                    return true;
                }
            }
        }
        return false;

    // Recognition by length of line
    case 'L':
        return line.length() >= lengthIdentMin && line.length() <= lengthIdentMax;
    }
    return true;
}

From source file:com.fsck.k9.helper.Utility.java

/**
 * Extract the 'original' subject value, by ignoring leading
 * response/forward marker and '[XX]' formatted tags (as many mailing-list
 * softwares do)./*from w w  w  . j a  v a 2  s  . co  m*/
 *
 * <p>
 * Result is also trimmed.
 * </p>
 *
 * @param subject
 *            Never <code>null</code>.
 * @return Never <code>null</code>.
 */
public static String stripSubject(final String subject) {
    int lastPrefix = 0;

    final Matcher tagMatcher = TAG_PATTERN.matcher(subject);
    String tag = null;
    // whether tag stripping logic should be active
    boolean tagPresent = false;
    // whether the last action stripped a tag
    boolean tagStripped = false;
    if (tagMatcher.find(0)) {
        tagPresent = true;
        if (tagMatcher.start() == 0) {
            // found at beginning of subject, considering it an actual tag
            tag = tagMatcher.group();

            // now need to find response marker after that tag
            lastPrefix = tagMatcher.end();
            tagStripped = true;
        }
    }

    final Matcher matcher = RESPONSE_PATTERN.matcher(subject);

    // while:
    // - lastPrefix is within the bounds
    // - response marker found at lastPrefix position
    // (to make sure we don't catch response markers that are part of
    // the actual subject)

    while (lastPrefix < subject.length() - 1 && matcher.find(lastPrefix) && matcher.start() == lastPrefix
            && (!tagPresent || tag == null || subject.regionMatches(matcher.end(), tag, 0, tag.length()))) {
        lastPrefix = matcher.end();

        if (tagPresent) {
            tagStripped = false;
            if (tag == null) {
                // attempt to find tag
                if (tagMatcher.start() == lastPrefix) {
                    tag = tagMatcher.group();
                    lastPrefix += tag.length();
                    tagStripped = true;
                }
            } else if (lastPrefix < subject.length() - 1 && subject.startsWith(tag, lastPrefix)) {
                // Re: [foo] Re: [foo] blah blah blah
                //               ^     ^
                //               ^     ^
                //               ^    new position
                //               ^
                //              initial position
                lastPrefix += tag.length();
                tagStripped = true;
            }
        }
    }
    // Null pointer check is to make the static analysis component of Eclipse happy.
    if (tagStripped && (tag != null)) {
        // restore the last tag
        lastPrefix -= tag.length();
    }
    if (lastPrefix > -1 && lastPrefix < subject.length() - 1) {
        return subject.substring(lastPrefix).trim();
    } else {
        return subject.trim();
    }
}