Example usage for java.util.regex Matcher region

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

Introduction

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

Prototype

public Matcher region(int start, int end) 

Source Link

Document

Sets the limits of this matcher's region.

Usage

From source file:ai.grakn.test.docs.DocTestUtil.java

static int getLineNumber(String data, int start) {
    int line = 1;
    Pattern pattern = Pattern.compile("\n");
    Matcher matcher = pattern.matcher(data);
    matcher.region(0, start);
    while (matcher.find()) {
        line++;//w  w w.java  2s .co  m
    }
    return line;
}

From source file:com.meltmedia.cadmium.servlets.BasicFileServlet.java

public static List<String> parseETagList(String value) {
    List<String> etags = new ArrayList<String>();
    value = value.trim();/*from  ww  w.ja v  a 2  s. c o m*/
    if ("*".equals(value)) {
        etags.add(value);
    } else {
        Matcher etagMatcher = etagPattern.matcher(value);
        while (etagMatcher.lookingAt()) {
            etags.add(unescapePattern.matcher(etagMatcher.group(2)).replaceAll("$1"));
            etagMatcher.region(etagMatcher.start() + etagMatcher.group().length(), value.length());
        }
        if (!etagMatcher.hitEnd()) {
            etags.clear();
        }
    }
    return etags;
}

From source file:com.intuit.tank.tools.debugger.FindReplaceDialog.java

private void find(RSyntaxTextArea textArea) {

    try {/* w w  w.  jav a 2s.com*/
        int offset = currentLine < textArea.getLineCount() ? textArea.getLineStartOffset(currentLine) : 0;
        String searchTerm = tfSearchEditor.getText();
        String text = textArea.getText();
        int foundIndex = -1;
        int flags = (checkboxRegexp.isSelected() ? 0 : Pattern.LITERAL)
                | (checkboxMatchCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE);
        Pattern p = Pattern.compile(searchTerm, flags);
        Matcher matcher = p.matcher(text);
        matcher.region(offset, text.length());
        if (matcher.find()) {
            foundIndex = matcher.start();
        } else if (checkboxWrap.isSelected() && offset > 0) {
            matcher.region(0, offset);
            if (matcher.find()) {
                foundIndex = matcher.start();
            }
        }
        if (foundIndex != -1) {
            int lineOfOffset = textArea.getLineOfOffset(foundIndex);
            // textArea.setActiveLineRange(lineOfOffset, lineOfOffset);
            textArea.setCurrentLine(lineOfOffset);
            // textArea.setCaretPosition(foundIndex + searchTerm.length());
            parent.repaint();
            parent.fireStepChanged(lineOfOffset);
            currentLine = lineOfOffset + 1;
        } else {
            JOptionPane.showMessageDialog(parent, "Search String not found.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java

@Override
public void addWhere(String where) {
    Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer);
    String alias = findAlias(entityMatcher);

    int insertPos = buffer.length();
    Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer);
    if (lastClauseMatcher.find(entityMatcher.end()))
        insertPos = lastClauseMatcher.start() - 1;

    StringBuilder sb = new StringBuilder();
    Matcher whereMatcher = WHERE_PATTERN.matcher(buffer);
    int whereEnd = -1;
    boolean needOpenBracket = false;
    if (whereMatcher.find(entityMatcher.end())) {
        whereEnd = whereMatcher.end();/*  w w  w  . ja  va 2  s.  c  o  m*/

        Matcher orMatcher = OR_PATTERN.matcher(buffer);
        orMatcher.region(whereEnd + 1, insertPos);
        if (orMatcher.find()) { // surround with brackets if there is OR inside WHERE
            sb.append(")");
            needOpenBracket = true;
        }
        sb.append(" and ");
    } else {
        sb.append(" where ");
    }

    sb.append("(").append(where);
    int idx;
    while ((idx = sb.indexOf(ALIAS_PLACEHOLDER)) >= 0) {
        sb.replace(idx, idx + ALIAS_PLACEHOLDER.length(), alias);
    }
    sb.append(")");

    if (needOpenBracket) {
        buffer.insert(whereEnd + 1, "(");
        insertPos++;
    }

    buffer.insert(insertPos, sb);

    Matcher paramMatcher = PARAM_PATTERN.matcher(where);
    while (paramMatcher.find()) {
        addedParams.add(paramMatcher.group(1));
    }
}

From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java

@Override
public void addJoinAndWhere(String join, String where) {
    Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer);
    String alias = findAlias(entityMatcher);

    int insertPos = buffer.length();

    Matcher whereMatcher = WHERE_PATTERN.matcher(buffer);
    if (whereMatcher.find(entityMatcher.end())) {
        insertPos = whereMatcher.start() - 1;
    } else {//from  w w  w .  ja v  a 2s .c om
        Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer);
        if (lastClauseMatcher.find(entityMatcher.end()))
            insertPos = lastClauseMatcher.start() - 1;
    }

    if (!StringUtils.isBlank(join)) {
        buffer.insert(insertPos, " ");
        insertPos++;
        buffer.insert(insertPos, join);

        Matcher paramMatcher = PARAM_PATTERN.matcher(join);
        while (paramMatcher.find()) {
            addedParams.add(paramMatcher.group(1));
        }
    }
    if (!StringUtils.isBlank(where)) {
        insertPos = buffer.length();
        Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer);
        if (lastClauseMatcher.find(entityMatcher.end()))
            insertPos = lastClauseMatcher.start() - 1;

        StringBuilder sb = new StringBuilder();
        whereMatcher = WHERE_PATTERN.matcher(buffer);
        int whereEnd = -1;
        boolean needOpenBracket = false;
        if (whereMatcher.find(entityMatcher.end())) {
            whereEnd = whereMatcher.end();

            Matcher orMatcher = OR_PATTERN.matcher(buffer);
            orMatcher.region(whereEnd + 1, insertPos);
            if (orMatcher.find()) { // surround with brackets if there is OR inside WHERE
                sb.append(")");
                needOpenBracket = true;
            }
            sb.append(" and ");
        } else {
            sb.append(" where ");
        }

        sb.append("(").append(where).append(")");

        if (needOpenBracket) {
            buffer.insert(whereEnd + 1, "(");
            insertPos++;
        }

        buffer.insert(insertPos, sb);

        Matcher paramMatcher = PARAM_PATTERN.matcher(where);
        while (paramMatcher.find()) {
            addedParams.add(paramMatcher.group(1));
        }
    }

    // replace ALIAS_PLACEHOLDER
    int idx;
    while ((idx = buffer.indexOf(ALIAS_PLACEHOLDER)) >= 0) {
        buffer.replace(idx, idx + ALIAS_PLACEHOLDER.length(), alias);
    }
}

From source file:jp.go.nict.langrid.wrapper.ws_1_2.translation.AbstractTranslationService.java

private String[] divideSource(String source, int maxSourceLength) {
    ArrayList<String> resultArray = new ArrayList<String>();

    Pattern p = Pattern.compile("(\\Q*$%*\\E|\\Q*%$*\\E)");
    Matcher m = p.matcher(source);

    int index = 0;
    int end = 0;//w w w.  ja  v  a2  s .  co  m
    while (index + maxSourceLength < source.length()) {
        Matcher region = m.region(index, index + maxSourceLength);
        while (region.find()) {
            end = m.end();
        }
        if (end > index) {
            resultArray.add(source.substring(index, end + 1));
            index = end + 2;
            end = index;
        } else {
            break;
        }
    }

    if (index < source.length()) {
        resultArray.add(source.substring(index));
    }

    return resultArray.toArray(new String[] {});
}

From source file:com.application.utils.FastDateParser.java

/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 *
 * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
 *///ww  w.  ja va2 s  . c o m
private void init(Calendar definingCalendar) {

    final StringBuilder regex = new StringBuilder();
    final List<Strategy> collector = new ArrayList<Strategy>();

    final Matcher patternMatcher = formatPattern.matcher(pattern);
    if (!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException(
                "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
    }

    currentFormatField = patternMatcher.group();
    Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
    for (;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if (!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        final String nextFormatField = patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField, definingCalendar);
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = nextFormatField;
        currentStrategy = nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException(
                "Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart());
    }
    if (currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField = null;
    strategies = collector.toArray(new Strategy[collector.size()]);
    parsePattern = Pattern.compile(regex.toString());
}

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

/**
 * Scans a string of options and builds OptionInfo objects for each option
 * found.//from  w w w.  java 2s  . c  o 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:org.diorite.chat.component.TextComponent.java

/**
 * Create new BaseComponent from legacy minecraft chat message.
 *
 * @param message legacy message.//from  www.  ja va 2 s. c o m
 *
 * @return equals BaseComponent for given message.
 */
public static BaseComponent fromLegacyText(final String message) {
    final TextComponent base = new TextComponent("");
    StringBuilder builder = new StringBuilder();
    TextComponent component = new TextComponent();
    final Matcher matcher = url.matcher(message);

    for (int i = 0; i < message.length(); i++) {
        char c = message.charAt(i);
        if (c == ChatColor.COLOR_CHAR) {
            i++;
            c = message.charAt(i);
            if ((c >= 'A') && (c <= 'Z')) {
                //noinspection MagicNumber
                c += 32;
            }
            ChatColor format = ChatColor.getByChar(c);
            if (format == null) {
                continue;
            }
            if (builder.length() > 0) {
                final TextComponent old = component;
                component = new TextComponent(old);
                old.setText(builder.toString());
                builder = new StringBuilder();
                base.addExtra(old);
            }
            switch (format) {
            case BOLD:
                component.setBold(true);
                break;
            case ITALIC:
                component.setItalic(true);
                break;
            case UNDERLINE:
                component.setUnderlined(true);
                break;
            case STRIKETHROUGH:
                component.setStrikethrough(true);
                break;
            case MAGIC:
                component.setObfuscated(true);
                break;
            case RESET:
                format = ChatColor.WHITE;
            default:
                component = new TextComponent();
                component.setColor(format);
                break;
            }
            continue;
        }
        int pos = message.indexOf(' ', i);
        if (pos == -1) {
            pos = message.length();
        }
        if (matcher.region(i, pos).find()) { //Web link handling

            if (builder.length() > 0) {
                final TextComponent old = component;
                component = new TextComponent(old);
                old.setText(builder.toString());
                builder = new StringBuilder();
                base.addExtra(old);
            }

            final TextComponent old = component;
            component = new TextComponent(old);
            final String urlString = message.substring(i, pos);
            component.setText(urlString);
            component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,
                    urlString.startsWith("http") ? urlString : ("http://" + urlString)));
            base.addExtra(component);
            i += pos - i - 1;
            component = old;
            continue;
        }
        builder.append(c);
    }
    if (builder.length() > 0) {
        component.setText(builder.toString());
        base.addExtra(component);
    }
    return base;
}

From source file:org.onosproject.d.config.ResourceIds.java

/**
 * Converts node-identifier element to a NodeKey.
 *
 * @param id to parse (node-identifier fragment between '/')
 * @return NodeKey (warning: returned namespace can be null, which should be interpreted as
 *         same as parent)// www  .  j  av a  2s  . c o  m
 */
private static NodeKey toNodeKey(String id) {
    Pattern nodeId = Pattern.compile(
            "^((?<prefix>[a-zA-Z_](?:[a-zA-Z0-9_.\\-]*)):)?" + "(?<identifier>[a-zA-Z_](?:[a-zA-Z0-9_.-]*))");

    Matcher nidMatcher = nodeId.matcher(id);
    if (!nidMatcher.find()) {
        throw new IllegalArgumentException("node identifier not found in " + id);
    }

    String prefix = nidMatcher.group("prefix");
    String identifier = nidMatcher.group("identifier");

    // key and val pattern is a bit loosened from RFC for simplicity
    Pattern preds = Pattern.compile("\\[\\s*(?<key>[^=\\s]+)\\s*=\\s*\\\"(?<val>[^\\]]+)\\\"\\s*\\]");
    Matcher predMatcher = preds.matcher(id);
    predMatcher.region(nidMatcher.end(), id.length());
    LeafListKeyBuilder llkb = null;
    ListKeyBuilder llb = null;
    while (predMatcher.find()) {
        String key = predMatcher.group("key");
        String val = predMatcher.group("val");
        if (key.equals(".")) {
            // LeafList
            if (llkb == null) {
                llkb = new LeafListKeyBuilder();
            }
            llkb.schemaId(identifier, prefix).value(val);
        } else {
            // ListKey
            if (llb == null) {
                llb = new ListKeyBuilder();
            }
            llb.schemaId(identifier, prefix);
            Matcher m = nodeId.matcher(key);
            m.matches();
            llb.addKeyLeaf(m.group("identifier"), m.group("prefix"), val);
        }
    }
    if (llkb != null) {
        return llkb.build();
    } else if (llb != null) {
        return llb.build();
    } else {
        return NodeKey.builder().schemaId(identifier, prefix).build();
    }
}