Example usage for com.google.gwt.regexp.shared RegExp getLastIndex

List of usage examples for com.google.gwt.regexp.shared RegExp getLastIndex

Introduction

In this page you can find the example usage for com.google.gwt.regexp.shared RegExp getLastIndex.

Prototype

public final int getLastIndex() 

Source Link

Usage

From source file:client.net.sf.saxon.ce.dom.HTMLNodeWrapper.java

License:Mozilla Public License

private String getStyleAttribute(Element elem) {
    // style attribute must exist and must be quoted properly
    // IE9 does not include style attributes text if their value is not valid
    // we therefore don't expect non-quoted styles like <h1 style=color id="abc"...
    String value = getOuterHTML(elem);

    RegExp quotesPattern = RegExp.compile("(?:\".*?\"|\'.*?\'|[^\'\"]+|['\"])", "g"); // g=global: = all-matches 
    RegExp stylePattern = RegExp.compile("[\\s]style\\s*="); // e.g. match: <h1 style=
    MatchResult m = quotesPattern.exec(value);

    int i = 0;/*ww w .  ja  v a2 s. c  o  m*/
    boolean styleFound = false;
    String styleContent = "";
    String nonQ = "";
    while (quotesPattern.getLastIndex() > 0) {
        if (i % 2 == 0) {
            nonQ = m.getGroup(0); // not in quotes - so check
            MatchResult ms = stylePattern.exec(nonQ);
            styleFound = ms.getGroupCount() > 0;
            if (!styleFound && nonQ.indexOf('>') > -1) {
                break; // no more attributes
            }
        } else if (styleFound) {
            styleContent = m.getGroup(0);
            // remove enclosing quotes
            styleContent = styleContent.substring(1, styleContent.length() - 1);
            break;
        }
        i++;
        m = quotesPattern.exec(value);
    }
    return styleContent;
}

From source file:client.net.sf.saxon.ce.dom.HTMLNodeWrapper.java

License:Mozilla Public License

private HTMLAttributeNode[] getAltAttributes() {
    if (attributeList != null) {
        return attributeList;
    }//  w ww.j  a va  2 s  .  c om
    Element elem = (Element) node;

    // Browser implementations of attributes property are potentially buggy - but preferred to
    // parsing the string. But IE6 and IE7 both list all possible attributes whether they
    // exist or not - so use outerHTML in these cases.
    int ieVersion = Configuration.getIeVersion();
    if (ieVersion < 0 || ieVersion > 8) {
        return getMainAttributes(elem);
    }

    String value = getOuterHTML(elem);

    if (value == null) {
        return getMainAttributes(elem);
    }

    ArrayList<String> nodeNames = new ArrayList<String>();
    ArrayList<String> xmlnsNames = new ArrayList<String>();
    ArrayList<String> xmlnsUris = new ArrayList<String>();
    namespaceBindings = new ArrayList<NamespaceBinding>();

    RegExp quotesPattern = RegExp.compile("(?:\"(.|\n)*?\"|\'(.|\n)*?\'|[^\'\"]+|['\"])", "gm"); // g=global: = all-matches m=multiline 
    MatchResult m = quotesPattern.exec(value);

    int i = 0;
    String nonQ = "";
    boolean awaitingXmlnsUri = false;
    while (quotesPattern.getLastIndex() > 0) {

        if (i % 2 == 0) {
            nonQ = m.getGroup(0); // not in quotes - so check
            StringBuffer sb = new StringBuffer();
            boolean endOfTag = false;
            boolean isName = !(i == 0);// first part is not a name: e.g. \r\n<H1 style="
            int start = 0;
            if (i == 0) {
                start = nonQ.indexOf('<') + 1;
            }
            for (int x = start; x < nonQ.length(); x++) {
                int[] offsetChar = skipWhitespace(x, nonQ, false);
                int offset = offsetChar[0];

                if (offset > 0 && !(isName)) {
                    // no whitespace allow in an unquoted value, so we're back on a name
                    isName = true;
                }
                char ch = (char) offsetChar[1];
                if (ch == '\0')
                    break;
                if (ch == '=') {
                    // part after the '=' is the value, until next whitespace
                    isName = false;
                    String attName = sb.toString();

                    if (attName.startsWith("xmlns")) {
                        xmlnsNames.add(attName);
                        awaitingXmlnsUri = true;
                    } else if (attName.length() != 0) {
                        nodeNames.add(attName);
                        awaitingXmlnsUri = false;
                    }

                    sb = new StringBuffer();
                    continue;
                } else if (ch == '>') {
                    endOfTag = true;
                    break;
                }

                if (isName) {
                    sb.append(ch);
                }
                x += offset;
            } // end for
            if (endOfTag) {
                break;
            }
        } else if (awaitingXmlnsUri) {// ends if i % 2
            xmlnsUris.add(m.getGroup(0));
        }
        i++;
        m = quotesPattern.exec(value);
    } // end while

    HTMLAttributeNode[] nodeArray = new HTMLAttributeNode[nodeNames.size()];
    for (int y = 0; y < nodeNames.size(); y++) {
        String name = nodeNames.get(y);
        String nValue = getAltAttribute(name); // elem.getAttribute(name);
        // must be html because using outerHTML attribute - so no namespaces
        HTMLAttributeNode hNode = new HTMLAttributeNode(this, name, "", "", nValue);
        nodeArray[y] = hNode;
    }
    int count = 0;
    for (String name : xmlnsNames) {
        // use substring to exclude xmlns: prefix
        boolean noPrefix = (name.length() == 5);
        String prefix = (noPrefix) ? "" : name.substring(6);
        // xmlns declarations with prefixes can't be fetched using getAttribute
        String attValue = (noPrefix) ? getAltAttribute(name) : trimEdgeChars(xmlnsUris.get(count));
        namespaceBindings.add(new NamespaceBinding(prefix, attValue));
        count++;
    }
    attributeList = nodeArray; // for later use
    attributeNames = nodeNames;
    return nodeArray;
}

From source file:com.google.collide.client.editor.search.SearchMatchRenderer.java

License:Open Source License

@Override
public boolean resetToBeginningOfLine(Line line, int lineNumber) {
    assert model.getQuery() != null;
    assert model.getSearchPattern() != null;

    edges.clear();/*from   www  .  ja  v  a2s . co  m*/
    String text = line.getText();
    RegExp regex = model.getSearchPattern();
    /*
     * We must not forget to clear the lastIndex since it is a global regex, if
     * we don't it can lead to a false negative for matches.
     */
    regex.setLastIndex(0);
    MatchResult match = regex.exec(text);
    if (match == null || match.getGroup(0).isEmpty()) {
        return false;
    }

    do {
        int start = regex.getLastIndex() - match.getGroup(0).length();
        edges.add(start);
        edges.add(regex.getLastIndex());
        match = regex.exec(text);
    } while (match != null && !match.getGroup(0).isEmpty());

    // Handles the edge cases of matching at beginning or end of a line
    inMatch = true;
    if (edges.get(0) != 0) {
        inMatch = false;
        edges.splice(0, 0, 0);
    }
    if (edges.peek() != text.length()) {
        edges.add(text.length());
    }

    return true;
}

From source file:com.google.collide.shared.util.RegExpUtils.java

License:Open Source License

/**
 * Creates a regular expression which will match the given wildcard pattern
 *
 *  Backslashes can be used to escape a wildcard character and make it a
 * literal; likewise, backslashes before wildcard characters can be escaped.
 *///from w  w w . jav  a 2s  .c o m
private static String createRegExpStringForWildcardPattern(String wildcardPattern) {
    String escaped = regexpWildcardEscape.replace(wildcardPattern, "\\$&");

    /**
     * We have already run the pattern through the naive regex escape which
     * escapes all characters except the * and ?. This leads to double escaped \
     * characters that we have to inspect to determine if the user escaped the
     * wildcard or if we should replace it with it's regex equivalent.
     *
     *  NOTE: * is replaced with \S+ (matches all non-whitespace characters) and
     * ? is replaced with a single \S to match any non-whitespace
     */
    RegExp mimicLookbehind = RegExp.compile("([\\\\]*)([?*])", "g");
    StringBuilder wildcardStr = new StringBuilder(escaped);

    for (MatchResult match = mimicLookbehind.exec(
            wildcardStr.toString()); match != null; match = mimicLookbehind.exec(wildcardStr.toString())) {
        // in some browsers an optional group is null, in others its empty string
        if (match.getGroup(1) != null && !match.getGroup(1).isEmpty()) {
            // We undo double-escaping of backslashes performed by the naive escape
            int offset = match.getGroup(1).length() / 2;
            wildcardStr.delete(match.getIndex(), match.getIndex() + offset);
            /*
             * An even number of slashes means the wildcard was not escaped so we
             * must replace it with its regex equivalent.
             */
            if (offset % 2 == 0) {
                if (match.getGroup(2).equals("?")) {
                    wildcardStr.replace(match.getIndex() + offset, match.getIndex() + offset + 1, "\\S");
                    // we added 1 more character, so we remove 1 less from the index
                    offset -= 1;
                } else {
                    wildcardStr.replace(match.getIndex() + offset, match.getIndex() + offset + 1, "\\S+");
                    // we added 2 characters, so we need to remove 2 less from the index
                    offset -= 2;
                }
            }
            mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() - offset);
        } else if (match.getGroup(2).equals("?")) {
            wildcardStr.replace(match.getIndex(), match.getIndex() + 1, "\\S");
            mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() + 1);
        } else {
            wildcardStr.replace(match.getIndex(), match.getIndex() + 1, "\\S+");
            mimicLookbehind.setLastIndex(mimicLookbehind.getLastIndex() + 2);
        }
    }

    return wildcardStr.toString();
}

From source file:fr.putnami.pwt.plugin.code.client.render.AbstractTextRendererAspect.java

License:Open Source License

private List<Token<?>> addEOLToken(String value, List<Token<?>> tokenList) {
    List<Token<?>> resultTokenList = Lists.newArrayList();
    // add EOL Tokens
    RegExp regExp = RegExp.compile(CharacterUtil.END_OF_LINE_PATTERN, "g");
    MatchResult eolMatcher = regExp.exec(value);
    while (eolMatcher != null) {
        for (Iterator<Token<?>> it = tokenList.iterator(); it.hasNext();) {
            Token<?> currToken = it.next();
            if (currToken.getTokenStart() >= regExp.getLastIndex()) {
                // current token is after last EL match
                break;
            }//from  w ww . j a  va 2s  .  c o  m
            if (this.getTokenEnd(currToken) <= eolMatcher.getIndex()) {
                // current token is before last EL match
                resultTokenList.add(currToken);
                it.remove();
            } else {
                // current token contains last EOL match
                it.remove();
                this.splitTokenAndAddEOL(tokenList, resultTokenList, it, regExp.getLastIndex(), eolMatcher,
                        currToken);
                break;
            }
        }
        eolMatcher = regExp.exec(value);
    }
    resultTokenList.addAll(tokenList);
    return resultTokenList;
}

From source file:org.eclipse.che.ide.editor.orion.client.WordDetectionUtil.java

License:Open Source License

public Position getWordAtOffset(Document document, int offset) {
    if (document == null) {
        return null;
    }//from   w  ww.jav  a2s.co m

    RegExp regExp = RegExp.compile(COMMON_WORD_REGEXP, "g");
    int line = document.getLineAtOffset(offset);
    String lineContent = document.getLineContent(line);
    int lineStart = document.getLineStart(line);

    int pos = offset - lineStart;
    int start = lineContent.lastIndexOf(' ', pos - 1) + 1;

    regExp.setLastIndex(start);
    MatchResult matchResult;
    while ((matchResult = regExp.exec(lineContent)) != null) {
        if (matchResult.getIndex() <= pos && regExp.getLastIndex() >= pos) {
            return new Position(matchResult.getIndex() + lineStart, matchResult.getGroup(0).length());
        }
    }
    return null;
}

From source file:org.jboss.errai.ui.nav.client.local.URLPatternMatcher.java

License:Apache License

/**
 * Generates a {@link URLPattern} from a {@link Page#path()}
 * @param urlTemplate The {@link Page#path()}
 * @return A {@link URLPattern} used to match URLs
 *//*from  ww w  . j a  va2s  .  c  om*/
public static URLPattern generatePattern(String urlTemplate) {
    final RegExp regex = RegExp.compile(URLPattern.paramRegex, "g");
    final List<String> paramList = new ArrayList<String>();

    MatchResult mr;
    final StringBuilder sb = new StringBuilder();

    // Ensure matching at beginning of line
    sb.append("^");
    // Match patterns with or without leading slash
    sb.append("/?");

    int endOfPreviousPattern = 0;
    int startOfNextPattern = 0;

    while ((mr = regex.exec(urlTemplate)) != null) {
        addParamName(paramList, mr);
        startOfNextPattern = mr.getIndex();

        // Append any string literal that may occur in the URL path
        // before the next parameter.
        sb.append(urlTemplate, endOfPreviousPattern, startOfNextPattern);

        // Append regex for matching the parameter value
        sb.append(URLPattern.urlSafe);

        endOfPreviousPattern = regex.getLastIndex();
    }

    // Append any remaining trailing string literals
    sb.append(urlTemplate, endOfPreviousPattern, urlTemplate.length());

    // Ensure matching at end of line
    sb.append("$");

    return new URLPattern(RegExp.compile(sb.toString()), paramList, urlTemplate);
}