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:com.edgenius.wiki.render.RenderUtil.java

/**
 * @param input//from  w w w. j  av  a 2 s .  c  o m
 * @param key
 * @param regions
 * @param newlineKey 
 * @return
 */
public static CharSequence createRegion(CharSequence input, String key, Collection<Region> regions,
        String newlineKey) {
    if (regions == null || regions.size() == 0)
        return input;

    //first, web split whole text by special border tag string some think like "key_regionKey_S|E"
    input = createRegionBorder(input, key, regions, newlineKey);

    //then we split them one by one. The split is dependent on the RegionComparator(), which ensure the split 
    //from end to start, and from inside to outside. And this makes easier on below replacement process.
    Set<Region> sortRegions = new TreeSet<Region>(new RegionComparator());
    sortRegions.addAll(regions);

    StringBuilder buf = new StringBuilder(input);
    StringBuilder regKey = new StringBuilder(key);
    int ks = key.length();
    for (Region region : sortRegions) {
        //See our issue http://bug.edgenius.com/issues/34
        //and SUN Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6337993
        Pattern pat = Pattern.compile(new StringBuilder(key).append(region.getKey()).append("S(.*?)")
                .append(key).append(region.getKey()).append("E").toString(), Pattern.DOTALL);
        try {
            Matcher matcher = pat.matcher(buf);
            if (matcher.find()) {
                region.setBody(matcher.group(1));
                buf.delete(matcher.start(), matcher.end());
                regKey.delete(ks, regKey.length());
                buf.insert(matcher.start(), regKey.append(region.getKey()).append(Region.REGION_SUFFIX));
            }
        } catch (StackOverflowError e) {
            AuditLogger.error("StackOverflow Error in RenderUtil.createRegion. Input[" + buf + "]  Pattern ["
                    + pat.pattern() + "]");
        } catch (Throwable e) {
            AuditLogger.error("Unexpected error in RenderUtil.createRegion. Input[" + buf + "]  Pattern ["
                    + pat.pattern() + "]", e);
        }
    }

    return buf;
}

From source file:com.github.abel533.mapperhelper.EntityHelper.java

/**
 * ?/*  www. jav a  2  s  . com*/
 */
public static String underlineToCamelhump(String str) {
    Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
    StringBuilder builder = new StringBuilder(str);
    for (int i = 0; matcher.find(); i++) {
        builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
    }
    if (Character.isUpperCase(builder.charAt(0))) {
        builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
    }
    return builder.toString();
}

From source file:com.logsniffer.util.grok.Grok.java

/**
 * Compiles a grok pattern and generates an internal standard pattern
 * representation for it.//w  w  w. ja  va2  s .c  o m
 * 
 * @param registry
 *            Groks registry for predefined types
 * @param pattern
 *            the grok pattern
 * @param flags
 *            flags corresponding to {@link Pattern#flags()}
 * @return a compiled grok pattern
 * @throws GrokException
 */
@SuppressWarnings("unchecked")
public static Grok compile(final GroksRegistry registry, final String pattern, final int flags)
        throws GrokException {
    final Grok g = new Grok();
    g.grokPattern = pattern;
    final StringBuilder compiledPattern = new StringBuilder();
    final Matcher m = PATTERN_SUBGROK.matcher(pattern);
    int lastPos = 0;
    g.typeConverters = new HashMap<>();
    while (m.find()) {
        final String left = pattern.substring(lastPos, m.start());
        lastPos = m.end();
        compiledPattern.append(left);
        int groupsCount = PatternHelper.countOpenParens(compiledPattern.toString(), compiledPattern.length());
        final String subGrokName = m.group(1);
        final String subGrokAttr = m.group(2);
        String subGrokType = m.group(3);
        final Grok subGrok = registry.getGroks().get(subGrokName);
        if (subGrok == null) {
            throw new GrokException("No predefined Grok pattern for name '" + subGrokName
                    + "' found used in pattern: " + pattern);
        }
        if (subGrokAttr != null) {
            compiledPattern.append("(");
            groupsCount++;
            g.groupNames.put(subGrokAttr, groupsCount);
        }
        if (subGrokType != null) {
            subGrokType = subGrokType.toLowerCase();
            if (supportedTypeConverters.containsKey(subGrokType)) {
                g.typeConverters.put(groupsCount,
                        (TypeConverter<Object>) supportedTypeConverters.get(subGrokType));
            } else {
                LOGGER.warn("Conversion type {} not support in grok pattern: {}", subGrokType, m.group(0));
            }
        }
        compiledPattern.append(subGrok.regexPattern.pattern());
        if (subGrokAttr != null) {
            compiledPattern.append(")");
        }
        for (final String subGrokSubAttr : subGrok.groupNames.keySet()) {
            final int subGrokGroup = subGrok.groupNames.get(subGrokSubAttr);
            g.groupNames.put(subGrokSubAttr, groupsCount + subGrokGroup);
            if (subGrok.typeConverters.get(subGrokGroup) != null) {
                g.typeConverters.put(groupsCount + subGrokGroup, subGrok.typeConverters.get(subGrokGroup));
            }
        }
    }
    compiledPattern.append(pattern.substring(lastPos));
    // g.regexPattern = Pattern.compile(compiledPattern.toString(), flags);
    final com.google.code.regexp.Pattern namedPattern = com.google.code.regexp.Pattern
            .compile(compiledPattern.toString(), flags);
    g.regexPattern = namedPattern.pattern();
    for (final String name : namedPattern.groupInfo().keySet()) {
        g.groupNames.put(name, namedPattern.groupInfo().get(name).get(0).groupIndex() + 1);
    }
    // Order groups by occurrence
    final List<Entry<String, Integer>> groups = new ArrayList<>(g.groupNames.entrySet());
    Collections.sort(groups, new Comparator<Entry<String, Integer>>() {
        @Override
        public int compare(final Entry<String, Integer> o1, final Entry<String, Integer> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });
    g.groupNames.clear();
    for (final Entry<String, Integer> entry : groups) {
        g.groupNames.put(entry.getKey(), entry.getValue());
    }
    LOGGER.debug("Compiled grok: {}", g);
    return g;
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderContext.java

/**
 * In tests we use "wbp:name" attribute to access widgets by such "internal" names, but UiBinder
 * does not like when it sees unknown attributes, so we should remove them.
 *///from   www  .  j  a  v a  2s  .co  m
private static String removeWbpNameAttributes(String content) {
    Matcher matcher = Pattern.compile("wbp:name=\"[^\"]*\"").matcher(content);
    // process each match
    int last = 0;
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        // not matched part
        sb.append(content.substring(last, start));
        last = end;
        // replace matched part with spaces
        for (int i = start; i < end; i++) {
            sb.append(' ');
        }
    }
    // append tail
    sb.append(content.substring(last));
    return sb.toString();
}

From source file:io.swagger.codegen.languages.AbstractSwift3Codegen.java

private static String normalizePath(String path) {
    StringBuilder builder = new StringBuilder();

    int cursor = 0;
    Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
    boolean found = matcher.find();
    while (found) {
        String stringBeforeMatch = path.substring(cursor, matcher.start());
        builder.append(stringBeforeMatch);

        String group = matcher.group().substring(1, matcher.group().length() - 1);
        group = camelize(group, true);//from ww  w.  j av a2s.  c  o m
        builder.append("{").append(group).append("}");

        cursor = matcher.end();
        found = matcher.find();
    }

    String stringAfterMatch = path.substring(cursor);
    builder.append(stringAfterMatch);

    return builder.toString();
}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

@Nonnull
public static String processMacroses(@Nonnull final String processingString,
        @Nonnull final PreprocessorContext context) {
    int position;
    String result = processingString;

    if (context.isAllowWhitespace()) {
        final Matcher matcher = PATTERN_MACROS_WITH_SPACES.matcher(processingString);
        final StringBuilder buffer = new StringBuilder();
        int end = 0;
        while (matcher.find()) {
            final int start = matcher.start();
            final int prevEnd = end;
            end = matcher.end();/*  w w w .  ja  va 2  s  .  c  om*/
            final String macrosBody = matcher.group(1);
            final Value value = Expression.evalExpression(macrosBody, context);
            buffer.append(processingString.substring(prevEnd, start));
            buffer.append(value.toString());
        }
        if (end < processingString.length()) {
            buffer.append(processingString.substring(end));
        }
        result = buffer.toString();
    } else {
        while (true) {
            position = result.indexOf("/*$");

            if (position >= 0) {
                final String leftPart = result.substring(0, position);
                final int beginIndex = position;
                position = result.indexOf("$*/", position);
                if (position >= 0) {
                    final String macrosBody = result.substring(beginIndex + 3, position);
                    final String rightPart = result.substring(position + 3);

                    final Value value = Expression.evalExpression(macrosBody, context);

                    result = leftPart + value.toString() + rightPart;
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }
    return result;
}

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.jaspersoft.jasperserver.api.engine.common.service.impl.ActionModel.java

private static String generateOptionLabel(ActionModelSupport actionModelContext, String labelExpression,
        String optionValue, String optionId) {
    //first substitute option value (assumes just one of these)
    labelExpression = labelExpression.replace(RES_OPTION_VALUE_SERVER, optionValue);
    labelExpression = labelExpression.replace(RES_OPTION_ID_SERVER, optionId);
    // now look for $R{...} pattern and resolve i18n value (assumes just one of these)
    Matcher matcher = RegexUtil.getResourceKeyPattern(resourceKeyRegularExpression).matcher(labelExpression);
    if (matcher.find()) {
        String resourceKeyPattern = labelExpression.substring(matcher.start(), matcher.end());
        String resourceKey = resourceKeyPattern.substring(3, resourceKeyPattern.length() - 1);
        String translation = getLocalizedValue(resourceKey, actionModelContext);
        return labelExpression.replace(resourceKeyPattern, translation);
    } else {/*from  www  .  j  av a  2s .  c o  m*/
        return labelExpression;
    }
}

From source file:com.bjond.utilities.MiscUtils.java

/**
* Given an original string this method will normalize all numerics held within
 * that string (if any) to allow for Natural Sort Ordering.
 *
 *  https://en.wikipedia.org/wiki/Natural_sort_order
 *
 *  Algorithm://from  w  w w  .  jav  a  2 s  . c o  m
 *  Our approach basically matches a precompiled regular expression against 
 *  a string and extracs all numeric substrings. This is standard and fast 
 *  regex concept that actually has a special match character: \d+
 *
 *  For each numeric normailze it and construct a new string with the normalized
 *  numeric in place of the original.
 *  
 *  Normalization in this instance is that each numeric contain the same number of
 *  places: 75. Each numeric less than 75 will be prepended with zeros. 
 *
 *  This algorithm can also be thought of as a mapping in which a numeric is
 *  mapped to another numeric that always contains 75 places.
 *
 *  Any numeric greater than 75 results in a bad order and a warning is emitted. 
 *  Nothing can be done beyond increasing the normailation places. Highly unlikely.
* 
 *  Implementation Notes:
 *  Emphasis on performance thus the code is a bit more complex than you would expect.
 *  I could make it even more complex and more performant (theoretically) by reducing
 *  temporary objects further but the resulting code would be exceedingly complex and 
 *  error prone. A balancing of the two requirements of maintainability and performance
 *  were considered.
 * 
* @param original
* @return
*/
public static String normalizeToNaturalSortOrder(final String original) {
    // Guard
    if (StringUtils.isBlank(original)) {
        return "";
    }

    // The normalized size of a numeric. 75 places
    final int NORMALIZED = 75;

    // Match on all numerics
    final Matcher m = numericPattern.matcher(original);

    // Flip through all numerics, if any, and normalize
    final StringBuilder sb = new StringBuilder(500);
    int index = 0; // Current location in string.
    while (m.find()) {
        final String numeric = original.substring(m.start(), m.end());

        // First insert any previous characters.
        sb.append(original.substring(index, m.start()));
        index = m.end();

        final int zeros = NORMALIZED - numeric.length();
        if (zeros > 0) { // if length > NORMALIZED we blew the sort.
            for (int i = 0; i < zeros; sb.append("0"), i++)
                ;
        } else {
            log.warn("Normalized numeric is greater than {} places. {}", NORMALIZED, original);
        }
        sb.append(numeric);
    }

    // Append anything non-numeric for the remainder of the string
    // if any.
    if (index < original.length()) {
        sb.append(original.substring(index));
    }

    return sb.toString();
}

From source file:com.twosigma.beaker.groovy.evaluator.GroovyEvaluator.java

static String envVariablesFilter(String p, Map<String, String> env) {

    if (p == null)
        return p;

    for (Pattern pattern : envVariablePatterns) {

        Matcher matcher = pattern.matcher(p);

        String r = "";

        int lastIndex = 0;

        while (matcher.find()) {

            String var = matcher.group(1);

            String substitute = env.get(var);

            if (substitute == null)
                substitute = "";

            r += p.substring(lastIndex, matcher.start());

            r += substitute;//  w ww .j a  v a  2s .  c om

            lastIndex = matcher.end();
        }

        r += p.substring(lastIndex, p.length());

        p = r;

    }

    return p;
}