Example usage for java.util.regex Matcher end

List of usage examples for java.util.regex Matcher end

Introduction

In this page you can find the example usage for java.util.regex Matcher end.

Prototype

public int end() 

Source Link

Document

Returns the offset after the last character matched.

Usage

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.spss.SPSSFileReader.java

int read_DataList(String dataListCommand) throws IOException {
    int readStatus = 0;

    // Read the first line (DATA LIST ...) to determine
    // the field separator:
    // This line should be "/"-terminated (?)

    dbgLog.fine("dataList command: " + dataListCommand);

    List<Integer> variableTypeList = new ArrayList<Integer>();
    Set<Integer> decimalVariableSet = new HashSet<Integer>();

    List<Integer> printFormatList = new ArrayList<Integer>(); // TODO: move
    Map<String, String> printFormatNameTable = new LinkedHashMap<String, String>(); // TODO: move

    String delimiterString = null;

    //String datalistRegex = "^data\\s+list\\s+list\\('(.)'\\)\\s+?/";
    String datalistRegex = "^list\\s*\\('(.)'\\)";
    Pattern datalistPattern = Pattern.compile(datalistRegex, java.util.regex.Pattern.CASE_INSENSITIVE);
    Matcher datalistMatcher = datalistPattern.matcher(dataListCommand);

    if (datalistMatcher.find()) {
        delimiterString = datalistMatcher.group(1);
        setDelimiterChar(delimiterString.charAt(0));
        dbgLog.fine("found delimiter: " + delimiterString);
    } else {//from   ww  w  .ja v  a 2  s.c  om
        throw new IOException(
                "Invalid SPSS Command Syntax: " + "no delimiter specified in the DATA LIST command.");
    }

    // Cut off the remaining lines containing the variable definitions:

    int separatorIndex = dataListCommand.indexOf("/");

    if (separatorIndex == -1) {
        throw new IOException("Invalid SPSS Command Syntax: " + "missing / delimiter on the DATA LIST line.");
        // No slash found after the first line of the Data List command.
    }

    dataListCommand = dataListCommand.substring(separatorIndex + 1);

    // Parse the variable section. For a delimited file this should be
    // a list of variable name + data type pairs.
    // "fortran" type definitions are assumed.

    dbgLog.fine("parsing " + dataListCommand + " for variable declarations.");

    int variableCounter = 0;

    String varName = null;
    String varType = null;

    String varDeclarationRegex = "^\\s*(\\S+)\\s+\\((\\S*)\\)";
    Pattern varDeclarationPattern = Pattern.compile(varDeclarationRegex);
    Matcher varDeclarationMatcher = varDeclarationPattern.matcher(dataListCommand);

    String stringVarDeclarationRegex = "^[aA]([0-9]+)";
    Pattern stringVarDeclarationPattern = Pattern.compile(stringVarDeclarationRegex);

    String numVarDeclarationRegex = "^[fF]([0-9]+)\\.*([0-9]*)";
    Pattern numVarDeclarationPattern = Pattern.compile(numVarDeclarationRegex);

    int endOfMatches = 0;

    while (varDeclarationMatcher.find()) {
        varName = varDeclarationMatcher.group(1);
        varType = varDeclarationMatcher.group(2);

        endOfMatches = varDeclarationMatcher.end();
        dataListCommand = dataListCommand.substring(endOfMatches);
        varDeclarationMatcher.reset(dataListCommand);

        dbgLog.fine("found variable " + varName + ", type " + varType);

        if (varType == null || varType.equals("")) {
            throw new IOException(
                    "Invalid variable declaration in DATA LIST command: no type specified for variable "
                            + varName + ".");

        }

        variableNameList.add(varName);

        // unfVariableTypes list holds extended type definitions for the
        // UNF calculation;
        // we need to be able to differentiate between Integers and
        // real numbers, in addition to the "numeric" and "string" values.

        varType = varType.toUpperCase();

        if (varType.startsWith("A")) {
            // String:

            Matcher stringVarDeclarationMatcher = stringVarDeclarationPattern.matcher(varType);
            if (stringVarDeclarationMatcher.find()) {
                variableTypeList.add(new Integer(stringVarDeclarationMatcher.group(1)));
            } else {
                // set to default if the string size is not explicitely
                // specified:
                variableTypeList.add(1);
            }

            formatCategoryTable.put(varName, SPSSConstants.FORMAT_CATEGORY_TABLE.get("A"));

            unfVariableTypes.put(varName, -1);

            printFormatList.add(1);
            //printFormatNameTable.put(varName, "A");

        } else if (varType.startsWith("F")) {
            // "minimal" format value is 0 -- numeric
            variableTypeList.add(0);
            formatCategoryTable.put(varName, SPSSConstants.FORMAT_CATEGORY_TABLE.get("F"));

            if (varType.equals("F")) {
                // abbreviated numeric type definition;
                // defaults to f10.0

                // for the purposes of the UNF calculations this is an integer:
                unfVariableTypes.put(varName, 0);

                printFormatList.add(5);
                //printFormatNameTable.put(varName, "F10.0");

            } else {
                Matcher numVarDeclarationMatcher = numVarDeclarationPattern.matcher(varType);
                if (numVarDeclarationMatcher.find()) {
                    Integer numLength = new Integer(numVarDeclarationMatcher.group(1));
                    Integer numDecimal = 0;
                    String optionalToken = numVarDeclarationMatcher.group(2);

                    if (optionalToken != null && !optionalToken.equals("")) {
                        numDecimal = new Integer(optionalToken);

                        if ((int) numDecimal > 0) {
                            unfVariableTypes.put(varName, 1);
                            decimalVariableSet.add(variableCounter);
                            printFormatNameTable.put(varName, "F" + numLength + "." + numDecimal);
                        }
                    }

                    printFormatList.add(5); // TODO: verify (should it be 0 instead?)

                } else {
                    // This does not look like a valid numeric type
                    // definition.
                    throw new IOException("Invalid variable declaration in the DATA LIST command: "
                            + "Illegal or unsupported numeric type definition for variable " + varName);

                }
            }

        } else if (varType.matches("^[1-9]$")) {
            // Another allowed SPSS abbreviation:
            // type (N) where N is [1-9] means a numeric decimal with
            // N decimal positions:

            variableTypeList.add(0);
            formatCategoryTable.put(varName, SPSSConstants.FORMAT_CATEGORY_TABLE.get("F"));

            Integer numDecimal = new Integer(varType);
            unfVariableTypes.put(varName, 1);
            decimalVariableSet.add(variableCounter);

            printFormatList.add(5); // TODO: verify (should it be 0 instead?)
            printFormatNameTable.put(varName, "F10." + numDecimal);

            // Check for various date and time formats that we support:
        } else if (SPSSConstants.FORMAT_CATEGORY_TABLE.get(varType) != null) {

            //if ( SPSSConstants.FORMAT_CATEGORY_TABLE.get(varType).equals("date")
            //    || SPSSConstants.FORMAT_CATEGORY_TABLE.get(varType).equals("time")
            //    || varType.equals("WKDAY")
            //    || varType.equals("MONTH")) {

            if (varType.equalsIgnoreCase("DATE") || varType.equalsIgnoreCase("DATETIME")) {

                variableTypeList.add(1);
                formatCategoryTable.put(varName, SPSSConstants.FORMAT_CATEGORY_TABLE.get(varType));
                unfVariableTypes.put(varName, -1);
                //printFormatList.add(); // TODO: confirm that this isn't needed.
                printFormatNameTable.put(varName, varType);

            } else {
                throw new IOException("Invalid variable declaration in DATA LIST command: "
                        + "unsupported variable type definition for variable " + varName + ".");

            }

        } else {
            // invalid/unrecognized variable type definition.
            throw new IOException("Invalid variable declaration in DATA LIST command: "
                    + "unknown or illegal type definition for variable " + varName + ".");
        }

        variableCounter++;

    }

    //dataListCommand = dataListCommand.substring(endOfMatches);

    // check to see if we've parsed the entire DATA LIST section:
    if (!dataListCommand.matches("^[ \t\n\r]*$")) {
        throw new IOException("Illegal control card syntax: "
                + "this portion of the DATA LIST command could not be parsed: " + dataListCommand);
    }

    smd.getFileInformation().put("varQnty", variableCounter);
    setVarQnty(variableCounter);
    dbgLog.fine("varQnty=" + getVarQnty());

    smd.setVariableName(variableNameList.toArray(new String[variableNameList.size()]));

    // "minimal" variable types: SPSS type binary definition:
    // 0 means numeric, >0 means string.

    smd.setVariableTypeMinimal(
            ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()])));

    // This is how the "discrete" and "continuous" numeric values are
    // distinguished in the data set metadata:

    smd.setDecimalVariables(decimalVariableSet);

    //TODO: smd.getFileInformation().put("caseWeightVariableName", caseWeightVariableName);

    dbgLog.info("<<<<<<");
    dbgLog.info("printFormatList = " + printFormatList);
    dbgLog.info("printFormatNameTable = " + printFormatNameTable);
    dbgLog.info("formatCategoryTable = " + formatCategoryTable);
    dbgLog.info(">>>>>>");

    smd.setVariableFormat(printFormatList);
    smd.setVariableFormatName(printFormatNameTable);
    smd.setVariableFormatCategory(formatCategoryTable); //TODO: verify

    return variableCounter;
}

From source file:com.android.email.activity.MessageView.java

/**
 * Reload the body from the provider cursor.  This must only be called from the UI thread.
 *
 * @param bodyText text part/*  www  .  j  ava2  s  .  c  o m*/
 * @param bodyHtml html part
 *
 * TODO deal with html vs text and many other issues
 */
private void reloadUiFromBody(String bodyText, String bodyHtml) {
    String text = null;
    mHtmlTextRaw = null;
    boolean hasImages = false;

    if (bodyHtml == null) {
        text = bodyText;
        /*
         * Convert the plain text to HTML
         */
        StringBuffer sb = new StringBuffer("<html><body>");
        if (text != null) {
            // Escape any inadvertent HTML in the text message
            text = EmailHtmlUtil.escapeCharacterToDisplay(text);
            // Find any embedded URL's and linkify
            Matcher m = Patterns.WEB_URL.matcher(text);
            while (m.find()) {
                int start = m.start();
                /*
                 * WEB_URL_PATTERN may match domain part of email address. To detect
                 * this false match, the character just before the matched string
                 * should not be '@'.
                 */
                if (start == 0 || text.charAt(start - 1) != '@') {
                    String url = m.group();
                    Matcher proto = WEB_URL_PROTOCOL.matcher(url);
                    String link;
                    if (proto.find()) {
                        // This is work around to force URL protocol part be lower case,
                        // because WebView could follow only lower case protocol link.
                        link = proto.group().toLowerCase() + url.substring(proto.end());
                    } else {
                        // Patterns.WEB_URL matches URL without protocol part,
                        // so added default protocol to link.
                        link = "http://" + url;
                    }
                    String href = String.format("<a href=\"%s\">%s</a>", link, url);
                    m.appendReplacement(sb, href);
                } else {
                    m.appendReplacement(sb, "$0");
                }
            }
            m.appendTail(sb);
        }
        sb.append("</body></html>");
        text = sb.toString();
    } else {
        text = bodyHtml;
        mHtmlTextRaw = bodyHtml;
        hasImages = IMG_TAG_START_REGEX.matcher(text).find();
    }

    mShowPicturesSection.setVisibility(hasImages ? View.VISIBLE : View.GONE);
    if (mMessageContentView != null) {
        mMessageContentView.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null);
    }

    // Ask for attachments after body
    mLoadAttachmentsTask = new LoadAttachmentsTask();
    mLoadAttachmentsTask.execute(mMessage.mId);
}

From source file:com.aliyun.odps.conf.Configuration.java

private String substituteVars(String expr) {
    if (expr == null) {
        return null;
    }//  w  w w.jav a 2  s .  co m
    Matcher match = varPat.matcher("");
    String eval = expr;
    for (int s = 0; s < MAX_SUBST; s++) {
        match.reset(eval);
        if (!match.find()) {
            return eval;
        }
        String var = match.group();
        var = var.substring(2, var.length() - 1); // remove ${ .. }
        String val = null;
        try {
            val = System.getProperty(var);
        } catch (SecurityException se) {
            LOG.warn("No permission to get system property: " + var);
        }
        if (val == null) {
            val = getRaw(var);
        }
        if (val == null) {
            return eval; // return literal ${var}: var is unbound
        }
        // substitute
        eval = eval.substring(0, match.start()) + val + eval.substring(match.end());
    }
    throw new IllegalStateException("Variable substitution depth too large: " + MAX_SUBST + " " + expr);
}

From source file:net.rptools.maptool.client.MapToolLineParser.java

/**
 * Scans a string of options and builds OptionInfo objects for each option
 * found.// w w w .j a v  a2s  .co  m
 * 
 * @param optionString
 *            A string containing a comma-delimited list of roll options.
 * @throws RollOptionException
 *             if any of the options are unknown or don't match the template
 *             for that option type.
 */
private List<OptionInfo> getRollOptionList(String optionString) throws RollOptionException {
    if (optionString == null)
        return null;

    List<OptionInfo> list = new ArrayList<OptionInfo>();
    optionString = optionString.trim();
    int start = 0;
    int endOfString = optionString.length();
    boolean atEnd = false;
    Pattern commaPattern = Pattern.compile("^\\s*,\\s*(?!$)");

    while (start < endOfString) {
        OptionInfo roi;
        if (atEnd) {
            // If last param didn't end with ",", there shouldn't have been another option
            throw new RollOptionException(I18N.getText("lineParser.rollOptionComma"));
        }
        // Eat the next option from string, and add parsed option to list
        roi = new OptionInfo(optionString, start);
        list.add(roi);
        start = roi.getEnd();
        // Eat any "," sitting between options
        Matcher matcher = commaPattern.matcher(optionString);
        matcher.region(start, endOfString);
        if (matcher.find()) {
            start = matcher.end();
            atEnd = false;
        } else {
            atEnd = true;
        }
    }

    return list;
}

From source file:de.dfki.iui.opentok.cordova.plugin.OpenTokPlugin.java

private int extractDp(JSONArray args, int index) throws JSONException {

    JSONException failure = null;/*  ww w .ja  v a 2  s  .co  m*/
    int result = 0;
    try {
        result = args.getInt(index);
    } catch (JSONException e) {
        failure = e;
    }

    if (failure != null) {
        String temp = args.getString(index);

        //simple decimal number pattern
        Pattern p = Pattern.compile("([+-]?\\d+([,.]\\d+)?)");
        Matcher m = p.matcher(temp);
        if (m.find()) {
            result = Integer.parseInt(temp.substring(m.start(), m.end()));
        }
    }

    return result;
}

From source file:org.openmrs.module.rheapocadapter.impl.HL7MessageTransformer.java

private Location getLocation(OBR obr) throws HL7Exception {
    String hl7Location = obr.getFillerField1().getValue();
    Location location = null;/*from w w w  .  j  a v a 2s .c om*/

    List<Location> locationsList = Context.getLocationService().getAllLocations();
    Context.getLocationService().getLocation(hl7Location);
    for (Location l : locationsList) {
        String des = l.getDescription();
        String fosaid = null;
        if (des != null) {
            fosaid = des.toString();
        }
        String elid = null;

        if (fosaid != null) {
            final Matcher matcher = Pattern.compile(":").matcher(fosaid);
            if (matcher.find()) {
                elid = fosaid.substring(matcher.end()).trim();
                if (elid.equals(hl7Location)) {
                    location = l;
                }
            }
        }
    }

    return (location == null) ? Context.getLocationService().getDefaultLocation() : location;
}

From source file:com.sinosoft.one.data.jade.statement.SimpleInterpreter.java

public void interpret(StatementRuntime runtime) {

    final List<Object> parametersAsList = new LinkedList<Object>();

    // ??  :name ??
    Matcher matcher = NAMED_PARAM_PATTERN.matcher(runtime.getSQL());
    if (!matcher.find()) {
        return;//from  w ww.  j a  v  a2  s. co  m
    }

    final StringBuilder builder = new StringBuilder();

    int index = 0;

    do {
        // ??????
        String name = matcher.group(1);
        if (NumberUtils.isDigits(name)) {
            name = matcher.group();//??
        }

        Object value = null;

        // ?  a.b.c ?? 
        int find = name.indexOf('.');
        if (find >= 0) {

            //   BeanWrapper ?
            Object bean = runtime.getParameters().get(name.substring(0, find));
            if (bean != null) {
                BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
                value = beanWrapper.getPropertyValue(name.substring(find + 1));
            }

        } else {
            // ?
            value = runtime.getParameters().get(name);
        }

        // ?
        builder.append(runtime.getSQL().substring(index, matcher.start()));

        if (value instanceof Collection<?>) {

            //  IN (...) ?
            builder.append('(');

            Collection<?> collection = (Collection<?>) value;

            if (collection.isEmpty()) {
                builder.append("NULL");
            } else {
                builder.append('?');
            }

            for (int i = 1; i < collection.size(); i++) {
                builder.append(", ?");
            }

            builder.append(')');

            // ??
            parametersAsList.addAll(collection);

        } else {
            // ?
            builder.append('?');

            // ??
            parametersAsList.add(value);
        }

        index = matcher.end();

    } while (matcher.find());

    // ?
    builder.append(runtime.getSQL().substring(index));
    runtime.setSQL(builder.toString());
    runtime.setArgs(parametersAsList.toArray());
}

From source file:com.gzj.tulip.jade.statement.SimpleInterpreter.java

@Override
public void interpret(StatementRuntime runtime) {

    final List<Object> parametersAsList = new LinkedList<Object>();

    // ??  :name ??
    Matcher matcher = NAMED_PARAM_PATTERN.matcher(runtime.getSQL());
    if (!matcher.find()) {
        return;//from  w ww  .  jav  a 2s .  c  om
    }

    final StringBuilder builder = new StringBuilder();

    int index = 0;

    do {
        // ??????
        String name = matcher.group(1);
        if (NumberUtils.isDigits(name)) {
            name = matcher.group();//??
        }

        Object value = null;

        // ?  a.b.c ?? 
        int find = name.indexOf('.');
        if (find >= 0) {

            //   BeanWrapper ?
            Object bean = runtime.getParameters().get(name.substring(0, find));
            if (bean != null) {
                BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
                value = beanWrapper.getPropertyValue(name.substring(find + 1));
            }

        } else {
            // ?
            value = runtime.getParameters().get(name);
        }

        // ?
        builder.append(runtime.getSQL().substring(index, matcher.start()));

        if (value instanceof Collection<?>) {

            //  IN (...) ?
            builder.append('(');

            Collection<?> collection = (Collection<?>) value;

            if (collection.isEmpty()) {
                builder.append("NULL");
            } else {
                builder.append('?');
            }

            for (int i = 1; i < collection.size(); i++) {
                builder.append(", ?");
            }

            builder.append(')');

            // ??
            parametersAsList.addAll(collection);

        } else {
            // ?
            builder.append('?');

            // ??
            parametersAsList.add(value);
        }

        index = matcher.end();

    } while (matcher.find());

    // ?
    builder.append(runtime.getSQL().substring(index));
    runtime.setSQL(builder.toString());
    runtime.setArgs(parametersAsList.toArray());
}

From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java

/**
 * Finds all the matches inside the string for the given regex pattern and returns the list of matched indexes.
 * //from   www .j a v  a  2  s .co m
 * @param regex {@link String} The regex pattern generated.
 * @param strToBeMatched {@link String} The string which is to be matched.
 * @return {@link List<{@link String}> The list of matched indexes.
 * @throws Exception if any exception or error occur.
 */
@Override
public List<String> findMatchedIndexesList(final String regex, final String strToBeMatched) throws UIException {
    List<String> matchedIndexList = null;
    try {
        if (!StringUtil.isNullOrEmpty(regex) && strToBeMatched != null) {
            matchedIndexList = new ArrayList<String>();
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(strToBeMatched);
            while (matcher.find()) {
                matchedIndexList.add(String.valueOf(matcher.start()));
                matchedIndexList.add(String.valueOf(matcher.end()));
            }
        }
    } catch (final PatternSyntaxException patternSyntaxException) {
        throw new UIException("Invalid Regex Pattern.");
    }
    return matchedIndexList;
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

public void initViewsAndRegisterDDLs(Dialect dialect, DDLGenerator.AddDDLEntry... addDDLEntries) {
    List<DDLGenerator.AddDDLEntry> ddls = getProfile().getAllDdls();

    for (DDLGenerator.AddDDLEntry ddlFile : ddls) {
        if (ddlFile.isReader()) {
            continue;
        }// w ww .j a va2s.  co m
        Matcher matcher = VIEW_NAME_PATTERN.matcher(ddlFile.getDdlText(dialect));
        int idx = 0;
        while (matcher.find(idx)) {
            externalViews.add(matcher.group(2).toLowerCase());
            idx = matcher.end();
        }
    }

    views = new HashSet<String>(externalViews);
    //        Add all i18n view names
    for (TableConfig tableConfig : tblNameToConfig.values()) {
        if (tableConfig.getI18nBaseEntityTblName() != null) {
            views.add(tableConfig.getI18nBaseEntityTblName());
        }
    }

    getProfile().addDdl(0, getAddDDL());

    if (addDDLEntries != null) {
        for (int i = addDDLEntries.length; i > 0; i--) {
            getProfile().addDdl(1, addDDLEntries[i - 1]);
        }
    }

}