Example usage for java.util.regex Matcher start

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

Introduction

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

Prototype

public int start() 

Source Link

Document

Returns the start index of the previous match.

Usage

From source file:qhindex.controller.SearchAuthorWorksController.java

private String correctAuthorWorkPublisher(String publisher) {
    publisher = publisher.split(",")[0];
    Pattern endingNumbersPatter = Pattern.compile("(\\((\\d|\\s|\\+|\\-)+\\)|\\d+|\\s+|,|-)+$");
    Matcher matcher = endingNumbersPatter.matcher(publisher);
    if (matcher.find(0)) {
        String corrected = publisher.substring(0, matcher.start()).trim();
        publisher = corrected;/* w  w w  .j a va2s.  c  o  m*/
    }
    return publisher;
}

From source file:it.bradipao.berengar.DbTool.java

public static String jsonMinify(String jsonString) {
    String tokenizer = "\"|(/\\*)|(\\*/)|(//)|\\n|\\r";
    String magic = "(\\\\)*$";
    Boolean in_string = false;/*w w w. j a  v  a 2s .  c  o m*/
    Boolean in_multiline_comment = false;
    Boolean in_singleline_comment = false;
    String tmp = "";
    String tmp2 = "";
    List<String> new_str = new ArrayList<String>();
    Integer from = 0;
    String lc = "";
    String rc = "";

    Pattern pattern = Pattern.compile(tokenizer);
    Matcher matcher = pattern.matcher(jsonString);

    Pattern magicPattern = Pattern.compile(magic);
    Matcher magicMatcher = null;
    Boolean foundMagic = false;

    if (!matcher.find())
        return jsonString;
    else
        matcher.reset();

    while (matcher.find()) {
        lc = jsonString.substring(0, matcher.start());
        rc = jsonString.substring(matcher.end(), jsonString.length());
        tmp = jsonString.substring(matcher.start(), matcher.end());

        if (!in_multiline_comment && !in_singleline_comment) {
            tmp2 = lc.substring(from);
            if (!in_string)
                tmp2 = tmp2.replaceAll("(\\n|\\r|\\s)*", "");
            new_str.add(tmp2);
        }
        from = matcher.end();

        if (tmp.charAt(0) == '\"' && !in_multiline_comment && !in_singleline_comment) {
            magicMatcher = magicPattern.matcher(lc);
            foundMagic = magicMatcher.find();
            if (!in_string || !foundMagic || (magicMatcher.end() - magicMatcher.start()) % 2 == 0) {
                in_string = !in_string;
            }
            from--;
            rc = jsonString.substring(from);
        } else if (tmp.startsWith("/*") && !in_string && !in_multiline_comment && !in_singleline_comment) {
            in_multiline_comment = true;
        } else if (tmp.startsWith("*/") && !in_string && in_multiline_comment && !in_singleline_comment) {
            in_multiline_comment = false;
        } else if (tmp.startsWith("//") && !in_string && !in_multiline_comment && !in_singleline_comment) {
            in_singleline_comment = true;
        } else if ((tmp.startsWith("\n") || tmp.startsWith("\r")) && !in_string && !in_multiline_comment
                && in_singleline_comment) {
            in_singleline_comment = false;
        } else if (!in_multiline_comment && !in_singleline_comment
                && !tmp.substring(0, 1).matches("\\n|\\r|\\s")) {
            new_str.add(tmp);
        }
    }

    new_str.add(rc);
    StringBuffer sb = new StringBuffer();
    for (String str : new_str)
        sb.append(str);

    return sb.toString();
}

From source file:com.googlecode.jsfFlex.filter.JsfFlexResourceFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = HttpServletRequest.class.cast(request);
    HttpServletResponse httpResponse = HttpServletResponse.class.cast(response);

    JsfFlexResponseWrapper jsfFlexResponseWrapper = new JsfFlexResponseWrapper(httpResponse);
    AbstractJsfFlexResource jsfFlexResource = AbstractJsfFlexResource.getInstance();

    String requestURI = httpRequest.getRequestURI();
    String[] requestURISplitted = requestURI.split("/");

    if (isRequestForResource(requestURI)) {
        /** If request is of resource, process it and return */
        jsfFlexResource.processRequestResource(httpResponse, requestURISplitted);
        return;//from w  w  w  .  j a v  a 2s  .c  o m
    }

    /** Perform the regular path of request/response */

    chain.doFilter(request, jsfFlexResponseWrapper);

    jsfFlexResponseWrapper.finishResponse();

    /** Finished with the usual path of request/response. Now specific for JSF Flex*/

    if (jsfFlexResponseWrapper.getContentType() != null
            && isValidContentType(jsfFlexResponseWrapper.getContentType())) {

        Matcher headMatcher = HEAD_PATTERN.matcher(jsfFlexResponseWrapper.toString());
        boolean headMatchedBoolean = headMatcher.find();

        PrintWriter actualWriter = httpResponse.getWriter();

        if (headMatchedBoolean) {
            int headMatchIndex = headMatcher.start();

            actualWriter.write(jsfFlexResponseWrapper.toString().substring(0, headMatchIndex + 5));

            Matcher endTagCharMatcher = END_TAG_CHAR_PATTERN.matcher(jsfFlexResponseWrapper.toString());
            endTagCharMatcher.find(headMatchIndex);

            int endTagCharIndex = endTagCharMatcher.start();

            actualWriter.write(
                    jsfFlexResponseWrapper.toString().substring(headMatchIndex + 5, endTagCharIndex + 1));

            if (isDebugMode) {
                actualWriter.write(META_HTTP_EQUIV_EXPIRE);
                actualWriter.write(META_HTTP_EQUIV_PRAGMA_NO_CACHE);
                actualWriter.write(META_HTTP_EQUIV_CACHE_CONTROL_NO_CACHE);
            }

            Collection<String> resourceCollection = jsfFlexResource.getResources();
            String resourceConvertedToScriptElements = constructResourceToScriptTags(resourceCollection,
                    requestURISplitted);

            actualWriter.write(resourceConvertedToScriptElements);

            actualWriter.write(jsfFlexResponseWrapper.toString().substring(endTagCharIndex + 1));

        } else {

            Matcher bodyMatcher = BODY_PATTERN.matcher(jsfFlexResponseWrapper.toString());
            boolean bodyMatched = bodyMatcher.find();

            if (bodyMatched) {
                int bodyMatchIndex = bodyMatcher.start();

                actualWriter.write(jsfFlexResponseWrapper.toString().substring(0, bodyMatchIndex));

                actualWriter.write(HEAD_START_TAG);

                if (isDebugMode) {
                    actualWriter.write(META_HTTP_EQUIV_EXPIRE);
                    actualWriter.write(META_HTTP_EQUIV_PRAGMA_NO_CACHE);
                    actualWriter.write(META_HTTP_EQUIV_CACHE_CONTROL_NO_CACHE);
                }

                Collection<String> resourceCollection = jsfFlexResource.getResources();
                String resourceConvertedToScriptElements = constructResourceToScriptTags(resourceCollection,
                        requestURISplitted);

                actualWriter.write(resourceConvertedToScriptElements);

                actualWriter.write(HEAD_END_TAG);

                actualWriter.write(jsfFlexResponseWrapper.toString().substring(bodyMatchIndex));
            } else {
                //Must not be for mxml components, so flush
                actualWriter.write(jsfFlexResponseWrapper.toString());
            }
        }

        actualWriter.flush();
    }

}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Creates fixed record.//from w  w  w  . j  a  v  a 2  s  .co m
 *
 * @param cswResponse response
 * @param recordId record id.
 * @return record data
 */
private String makeResourceFromCswResponse(String cswResponse, String recordId) {
    Pattern cswRecordStart = Pattern.compile("<csw:Record>");
    Pattern cswRecordEnd = Pattern.compile("</csw:Record>");

    Matcher cswRecordStartMatcher = cswRecordStart.matcher(cswResponse);
    Matcher cswRecordEndMatcher = cswRecordEnd.matcher(cswResponse);

    if (cswRecordStartMatcher.find() && cswRecordEndMatcher.find()) {
        String dcResponse = cswResponse.substring(cswRecordStartMatcher.end(), cswRecordEndMatcher.start());
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<?xml version=\"1.0\"?><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:ows=\"http://www.opengis.net/ows\" xmlns:dct=\"http://purl.org/dc/terms/\">");
        xml.append("<rdf:Description ");
        if (recordId.length() > 0) {
            xml.append("rdf:about=\"").append(StringEscapeUtils.escapeXml11(recordId)).append("\"");
        }
        xml.append(">");

        xml.append(dcResponse);

        xml.append("</rdf:Description>");
        xml.append("</rdf:RDF>");

        return xml.toString();
    }

    return cswResponse;
}

From source file:com.haulmont.cuba.core.sys.AbstractMessages.java

@Override
public String getMessage(Enum caller, Locale locale) {
    checkNotNullArgument(caller, "Enum parameter 'caller' is null");

    String className = caller.getClass().getName();
    int i = className.lastIndexOf('.');
    if (i > -1)
        className = className.substring(i + 1);
    // If enum has inner subclasses, its class name ends with "$1", "$2", ... suffixes. Cut them off.
    Matcher matcher = enumSubclassPattern.matcher(className);
    if (matcher.find()) {
        className = className.substring(0, matcher.start());
    }//w w  w.j  ava  2 s  .  c  o m

    return getMessage(getPackName(caller.getClass()), className + "." + caller.name(), locale);
}

From source file:mergedoc.core.JavaBuffer.java

/**
 * ???????/*from   www  .j a  v a 2 s .  co m*/
 * ?????????
 * ????????????
 * @return ????? true
 */
public boolean nextComment() {

    while (commentMatcher.find()) {

        // ???????
        // /*******************/
        // JDK1.4 java.io.ObjectStreamConstants ??
        String sourceComment = getSourceComment();
        if (FastStringUtils.matches(sourceComment, "\\s*/\\*+/\\s*\n")) {
            continue;
        }

        // ??????
        if (sourceComment.contains(DUMMY_COMMENT)) {
            getSignature(); //??????
            commentMatcher.appendReplacement(outputBuffer, "");
            continue;
        }

        // ?????????
        Matcher nextMat = commentPattern.matcher(source);
        int currentEnd = commentMatcher.end();
        if (nextMat.find(currentEnd)) {
            String c2c = source.substring(currentEnd, nextMat.start());
            // ?(java.awt.GridBagLayoutorg.omg.PortableServer.Servant??)
            c2c = PatternCache.getPattern("(?s)/\\*(?:[^\\*].*?)?\\*/").matcher(c2c).replaceAll("");
            c2c = PatternCache.getPattern("//.*").matcher(c2c).replaceAll("");
            if (FastStringUtils.matches(c2c, "\\s*")) {
                continue;
            }
        }

        return true;
    }
    return false;
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * Helper method, taking a XML string like <ows:Metadata xmlns:ows=\"http://ogc.org/ows\" xmlns:xlink=\"http://wrc.org/xlink\" 
 * xlink:href=\"http://dude.com\"></ows:Metadata> from the reference 
 * and checks if /*from w  w  w  .ja va2  s  . c o m*/
 * a  the used prefixes match the globally used ones and
 * b) any of the declared namespaces are redundant 
 * 
 * The same is true for the XPath definition
 * 
 * @param resultingXMLString
 * @param context
 */
private void processNamespace(StringBuilder sb, NamespaceContext global, LocalNamespaceContext local) {

    Matcher prefixMatcher = prefixPattern.matcher(sb);
    Matcher nsMatcher = nsPattern.matcher(sb);
    String prefix;
    String uri;

    /* process the local namespaces */
    while (nsMatcher.find()) {
        int start = nsMatcher.start();
        int end = nsMatcher.end();
        StringBuilder sbu = new StringBuilder(sb.substring(start, end));
        String thisPrefix = sbu.substring(sbu.indexOf(":") + 1, sbu.lastIndexOf("="));
        String thisUri = sbu.substring(sbu.indexOf("\"") + 1, sbu.lastIndexOf("\""));
        // add to local namespace context
        local.put(thisPrefix, thisUri);

        if ((prefix = global.getPrefix(thisUri)) != null) {
            // namespace is registered, let's remove it
            sb.delete(start - 1, end);

            // we have to reset, since we changed the state of the matched string with the deletion
            nsMatcher.reset();
        }

    }

    /* change the prefixes */
    try {
        while (prefixMatcher.find()) {
            int start = prefixMatcher.start();
            int end = prefixMatcher.end();

            String localprefix = sb.substring(start + 1, end - 1);
            if ((global.getNamespaceURI(localprefix) == null)
                    && (uri = local.getNamespaceURI(localprefix)) != null) {
                // get the other prefix
                prefix = global.getPrefix(uri);

                if ((prefix != null) && (!(localprefix.contentEquals(prefix)))) {
                    sb.replace(start + 1, end - 1, prefix);
                    prefixMatcher.reset();
                }
            }
        }
    } catch (StringIndexOutOfBoundsException e) {
        // we do nothing here
    }

}

From source file:com.xpn.xwiki.render.filter.StyleFilter.java

public void handleMatch(StringBuffer buffer, MatchResult result, FilterContext context) {
    String command = result.group(1);

    if (command != null) {
        // {$peng} are variables not macros.
        if (!command.startsWith("$")) {
            MacroParameter mParams = context.getMacroParameter();
            switch (result.groups()) {
            case 3:
                mParams.setContent(result.group(3));
                mParams.setContentStart(result.beginOffset(3));
                mParams.setContentEnd(result.endOffset(3));
            case 2:
                mParams.setParams(result.group(2));
            }/*from  ww w.ja va  2  s.  c  o  m*/
            mParams.setStart(result.beginOffset(0));
            mParams.setEnd(result.endOffset(0));

            // @DANGER: recursive calls may replace macros in included source code
            try {
                if (command.equals("style") && (mParams.getContent() != null)) {
                    // We need to handle recursivity here
                    String content = mParams.getContent();
                    Pattern pattern = Pattern.compile("\\{" + command + ".*?\\}");

                    // This code allows to find the real end tag
                    Matcher matcher = pattern.matcher(content);
                    int startTagNumber = 1;
                    int endPosition = content.length();
                    while (matcher.find()) {
                        String match = matcher.group();
                        if (match.equals("{" + command + "}")) {
                            startTagNumber--;
                            if (startTagNumber == 0) {
                                endPosition = matcher.start();
                                break;
                            }
                        } else {
                            startTagNumber++;
                        }
                    }

                    // Get the content up to the real end tag
                    String realContent = content.substring(0, endPosition);

                    // Execute any nested macros and filters
                    mParams.setContent(realContent);
                    Writer writer = new StringBufferWriter(buffer);
                    Macro macro = (Macro) getMacroRepository().get(command);
                    // Execute the macro resulting content
                    macro.execute(writer, mParams);

                    if (content.length() != endPosition) {
                        // Get the content after the real end tag
                        String nextContent = content.substring(endPosition + 2 + command.length()) + "{style}";
                        // Execute other macros on content after the real end tag
                        writer.append(nextContent);
                    }
                } else if (getMacroRepository().containsKey(command)) {
                    Macro macro = (Macro) getMacroRepository().get(command);
                    // recursively filter macros within macros
                    if (null != mParams.getContent()) {
                        mParams.setContent(mParams.getContent());
                    }

                    Writer writer = new StringBufferWriter(buffer);
                    macro.execute(writer, mParams);
                } else {
                    buffer.append(result.group(0));
                    return;
                }
            } catch (IllegalArgumentException e) {
                buffer.append("<div class=\"error\">" + command + ": " + e.getMessage() + "</div>");
            } catch (Throwable e) {
                log.warn("MacroFilter: unable to format macro: " + result.group(1), e);
                buffer.append("<div class=\"error\">" + command + ": " + e.getMessage() + "</div>");
                return;
            }
        } else {
            buffer.append("<");
            buffer.append(command.substring(1));
            buffer.append(">");
        }
    } else {
        buffer.append(result.group(0));
    }
}

From source file:com.adgear.data.plugin.IDLSchemaMojo.java

/**
 * Inspect the source for dependency requirement statements
 *
 * @param source IDL source code//from  ww  w  . java2  s . c  o  m
 * @return Collection of dependency names
 */
protected Collection<String> collectDependencies(String source) {
    HashSet<String> found = new HashSet<String>();
    Matcher start = Pattern.compile("/\\*\\*", Pattern.MULTILINE).matcher(source);
    Matcher end = Pattern.compile("\\*/", Pattern.MULTILINE).matcher(source);
    if (start.find() && end.find()) {
        String doc = source.substring(start.start() + 3, end.end() - 2);
        Matcher dep = docstringPattern.matcher(doc);
        if (dep.find()) {
            Matcher required = Pattern.compile("([a-zA-Z0-9$_\\.]+)", Pattern.MULTILINE).matcher(dep.group(1));
            while (required.find()) {
                String name = required.group(1);
                found.add(name);
                getLog().debug("Registering dependency '" + name + "'");
            }
        }
    }
    return found;
}

From source file:ch.njol.skript.command.Commands.java

@Nullable
public final static ScriptCommand loadCommand(final SectionNode node) {
    final String key = node.getKey();
    if (key == null)
        return null;
    final String s = ScriptLoader.replaceOptions(key);

    int level = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '[') {
            level++;//  w w  w .  jav a  2  s .  c o  m
        } else if (s.charAt(i) == ']') {
            if (level == 0) {
                Skript.error("Invalid placement of [optional brackets]");
                return null;
            }
            level--;
        }
    }
    if (level > 0) {
        Skript.error("Invalid amount of [optional brackets]");
        return null;
    }

    Matcher m = commandPattern.matcher(s);
    final boolean a = m.matches();
    assert a;

    final String command = "" + m.group(1).toLowerCase();
    final ScriptCommand existingCommand = commands.get(command);
    if (existingCommand != null && existingCommand.getLabel().equals(command)) {
        final File f = existingCommand.getScript();
        Skript.error("A command with the name /" + command + " is already defined"
                + (f == null ? "" : " in " + f.getName()));
        return null;
    }

    final String arguments = m.group(3) == null ? "" : m.group(3);
    final StringBuilder pattern = new StringBuilder();

    List<Argument<?>> currentArguments = new ArrayList<Argument<?>>();
    m = argumentPattern.matcher(arguments);
    int lastEnd = 0;
    int optionals = 0;
    for (int i = 0; m.find(); i++) {
        pattern.append(escape("" + arguments.substring(lastEnd, m.start())));
        optionals += StringUtils.count(arguments, '[', lastEnd, m.start());
        optionals -= StringUtils.count(arguments, ']', lastEnd, m.start());

        lastEnd = m.end();

        ClassInfo<?> c;
        c = Classes.getClassInfoFromUserInput("" + m.group(2));
        final NonNullPair<String, Boolean> p = Utils.getEnglishPlural("" + m.group(2));
        if (c == null)
            c = Classes.getClassInfoFromUserInput(p.getFirst());
        if (c == null) {
            Skript.error("Unknown type '" + m.group(2) + "'");
            return null;
        }
        final Parser<?> parser = c.getParser();
        if (parser == null || !parser.canParse(ParseContext.COMMAND)) {
            Skript.error("Can't use " + c + " as argument of a command");
            return null;
        }

        final Argument<?> arg = Argument.newInstance(m.group(1), c, m.group(3), i, !p.getSecond(),
                optionals > 0);
        if (arg == null)
            return null;
        currentArguments.add(arg);

        if (arg.isOptional() && optionals == 0) {
            pattern.append('[');
            optionals++;
        }
        pattern.append("%" + (arg.isOptional() ? "-" : "")
                + Utils.toEnglishPlural(c.getCodeName(), p.getSecond()) + "%");
    }

    pattern.append(escape("" + arguments.substring(lastEnd)));
    optionals += StringUtils.count(arguments, '[', lastEnd);
    optionals -= StringUtils.count(arguments, ']', lastEnd);
    for (int i = 0; i < optionals; i++)
        pattern.append(']');

    String desc = "/" + command + " ";
    final boolean wasLocal = Language.setUseLocal(true); // use localised class names in description
    try {
        desc += StringUtils.replaceAll(pattern, "(?<!\\\\)%-?(.+?)%", new Callback<String, Matcher>() {
            @Override
            public String run(final @Nullable Matcher m) {
                assert m != null;
                final NonNullPair<String, Boolean> p = Utils.getEnglishPlural("" + m.group(1));
                final String s = p.getFirst();
                return "<" + Classes.getClassInfo(s).getName().toString(p.getSecond()) + ">";
            }
        });
    } finally {
        Language.setUseLocal(wasLocal);
    }
    desc = unescape(desc);
    desc = "" + desc.trim();

    node.convertToEntries(0);
    commandStructure.validate(node);
    if (!(node.get("trigger") instanceof SectionNode))
        return null;

    final String usage = ScriptLoader.replaceOptions(node.get("usage", desc));
    final String description = ScriptLoader.replaceOptions(node.get("description", ""));
    ArrayList<String> aliases = new ArrayList<String>(
            Arrays.asList(ScriptLoader.replaceOptions(node.get("aliases", "")).split("\\s*,\\s*/?")));
    if (aliases.get(0).startsWith("/"))
        aliases.set(0, aliases.get(0).substring(1));
    else if (aliases.get(0).isEmpty())
        aliases = new ArrayList<String>(0);
    final String permission = ScriptLoader.replaceOptions(node.get("permission", ""));
    final String permissionMessage = ScriptLoader.replaceOptions(node.get("permission message", ""));
    final SectionNode trigger = (SectionNode) node.get("trigger");
    if (trigger == null)
        return null;
    final String[] by = ScriptLoader.replaceOptions(node.get("executable by", "console,players"))
            .split("\\s*,\\s*|\\s+(and|or)\\s+");
    int executableBy = 0;
    for (final String b : by) {
        if (b.equalsIgnoreCase("console") || b.equalsIgnoreCase("the console")) {
            executableBy |= ScriptCommand.CONSOLE;
        } else if (b.equalsIgnoreCase("players") || b.equalsIgnoreCase("player")) {
            executableBy |= ScriptCommand.PLAYERS;
        } else {
            Skript.warning(
                    "'executable by' should be either be 'players', 'console', or both, but found '" + b + "'");
        }
    }

    if (!permissionMessage.isEmpty() && permission.isEmpty()) {
        Skript.warning("command /" + command + " has a permission message set, but not a permission");
    }

    if (Skript.debug() || node.debug())
        Skript.debug("command " + desc + ":");

    final File config = node.getConfig().getFile();
    if (config == null) {
        assert false;
        return null;
    }

    Commands.currentArguments = currentArguments;
    final ScriptCommand c;
    try {
        c = new ScriptCommand(config, command, "" + pattern.toString(), currentArguments, description, usage,
                aliases, permission, permissionMessage, executableBy, ScriptLoader.loadItems(trigger));
    } finally {
        Commands.currentArguments = null;
    }

    registerCommand(c);

    if (Skript.logVeryHigh() && !Skript.debug())
        Skript.info("registered command " + desc);
    currentArguments = null;
    return c;
}