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:Main.java

/**
 * Unescapes an escaped file or directory name back to its original value.
 *
 * <p>See {@link #escapeFileName(String)} for more information.
 *
 * @param fileName File name to be unescaped.
 * @return The original value of the file name before it was escaped,
 *    or null if the escaped fileName seems invalid.
 *//*from  ww w.jav a  2 s .c o m*/
public static String unescapeFileName(String fileName) {
    int length = fileName.length();
    int percentCharacterCount = 0;
    for (int i = 0; i < length; i++) {
        if (fileName.charAt(i) == '%') {
            percentCharacterCount++;
        }
    }
    if (percentCharacterCount == 0) {
        return fileName;
    }

    int expectedLength = length - percentCharacterCount * 2;
    StringBuilder builder = new StringBuilder(expectedLength);
    Matcher matcher = ESCAPED_CHARACTER_PATTERN.matcher(fileName);
    int endOfLastMatch = 0;
    while (percentCharacterCount > 0 && matcher.find()) {
        char unescapedCharacter = (char) Integer.parseInt(matcher.group(1), 16);
        builder.append(fileName, endOfLastMatch, matcher.start()).append(unescapedCharacter);
        endOfLastMatch = matcher.end();
        percentCharacterCount--;
    }
    if (endOfLastMatch < length) {
        builder.append(fileName, endOfLastMatch, length);
    }
    if (builder.length() != expectedLength) {
        return null;
    }
    return builder.toString();
}

From source file:Main.java

public static CharSequence replace(Context ctx, String text) {
    SpannableString spannableString = new SpannableString(text);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        String factText = matcher.group();
        String key = factText.substring(1);
        if (emotionTexts.contains(factText)) {
            Bitmap bitmap = getDrawableByName(ctx, key);
            ImageSpan image = new ImageSpan(ctx, bitmap);
            int start = matcher.start();
            int end = matcher.end();
            spannableString.setSpan(image, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }//from ww w  .  ja va2  s.c  om
    }
    return spannableString;
}

From source file:Main.java

public static CharSequence replace(Context ctx, String text) {
    if (text == null) {
        return null;
    }/*ww  w  .  j  a  v a 2s.  com*/
    SpannableString spannableString = new SpannableString(text);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        String factText = matcher.group();
        String key = factText.substring(1);
        if (emotionTexts.contains(factText)) {
            Bitmap bitmap = getDrawableByName(ctx, key);
            ImageSpan image = new ImageSpan(ctx, bitmap);
            int start = matcher.start();
            int end = matcher.end();
            spannableString.setSpan(image, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableString;
}

From source file:Main.java

public static void makeAboutSpannable(SpannableStringBuilder span, String str_link, String replace,
        final Runnable on_click) {
    Pattern pattern = Pattern.compile(str_link);
    Matcher matcher = pattern.matcher(span);
    ForegroundColorSpan color_theme = new ForegroundColorSpan(Color.parseColor("#53b7bb"));
    if (matcher.find()) {
        span.setSpan(new ClickableSpan() {
            @Override//w  w  w.  j ava  2s.c o  m
            public void onClick(View widget) {
                if (on_click != null)
                    on_click.run();
            }
        }, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(color_theme, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (replace != null)
            span.replace(matcher.start(), matcher.end(), replace);
    }
}

From source file:com.microsoft.tfs.util.PlatformVersion.java

/**
 * Returns the integer components of the given version number string.
 * "Components" are defined as any non-alphanumeric separated string of
 * alphanumeric characters. Only the integer components are returned and
 * only up to a non-integer component. For example, given the
 * "10_4.21Q.Z.14", the return will be [ 10, 4, 21 ].
 *
 * @param versionString/*from   w ww .  j a va2  s  .  c o m*/
 *        The version number string
 * @return An integer array of the numeric components of the version number
 *         string
 */
static final int[] parseVersionNumber(final String versionString) {
    if (versionString == null || versionString.length() == 0) {
        return new int[0];
    }

    /*
     * Split into component pieces -- everything that is non-alphanumeric is
     * considered a version number separator.
     */
    final String[] stringComponents = versionString.split("[^a-zA-Z0-9]"); //$NON-NLS-1$
    final ArrayList versionComponents = new ArrayList();

    /*
     * We trim components to keep only the leading numeric value.
     */
    synchronized (PlatformVersion.class) {
        if (componentPattern == null) {
            try {
                componentPattern = Pattern.compile("^([0-9]+)"); //$NON-NLS-1$
            } catch (final Exception e) {
                logger.error("Could not compile version number regex", e); //$NON-NLS-1$
                return new int[0];
            }
        }
    }

    for (int i = 0; i < stringComponents.length; i++) {
        /*
         * Trim to keep only the leading numeric value. If we're left with
         * nothing (ie, this component started with a letter), then do not
         * add it to the version number and stop.
         */
        final Matcher match = componentPattern.matcher(stringComponents[i]);

        if (match.find()) {
            try {
                versionComponents.add(new Integer(stringComponents[i].substring(match.start(), match.end())));
            } catch (final Exception e) {
                logger.warn("Could not coerce version number into format: " + versionString, e); //$NON-NLS-1$
                break;
            }
        } else {
            /* Component did not start with a numeric value, stopping. */
            break;
        }
    }

    /* Strip trailing zeroes. */
    while (versionComponents.size() > 0
            && versionComponents.get(versionComponents.size() - 1).equals(INTEGER_ZERO)) {
        versionComponents.remove(versionComponents.size() - 1);
    }

    /* Convert to int array */
    final int[] version = new int[versionComponents.size()];

    for (int i = 0; i < versionComponents.size(); i++) {
        version[i] = ((Integer) versionComponents.get(i)).intValue();
    }

    return version;
}

From source file:org.apache.asterix.api.http.server.ResultUtil.java

public static String buildParseExceptionMessage(Throwable e, String query) {
    StringBuilder errorMessage = new StringBuilder();
    String message = e.getMessage();
    message = message.replace("<", "&lt");
    message = message.replace(">", "&gt");
    errorMessage.append("Error: " + message + "\n");
    int pos = message.indexOf("line");
    if (pos > 0) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(message);
        if (m.find(pos)) {
            int lineNo = Integer.parseInt(message.substring(m.start(), m.end()));
            String[] lines = query.split("\n");
            if (lineNo > lines.length) {
                errorMessage.append("===> &ltBLANK LINE&gt \n");
            } else {
                String line = lines[lineNo - 1];
                errorMessage.append("==> " + line);
            }//from w  w  w .  j  a v  a 2s. c  o  m
        }
    }
    return errorMessage.toString();
}

From source file:edu.uci.ics.asterix.result.ResultUtils.java

public static String buildParseExceptionMessage(Throwable e, String query) {
    StringBuilder errorMessage = new StringBuilder();
    String message = e.getMessage();
    message = message.replace("<", "&lt");
    message = message.replace(">", "&gt");
    errorMessage.append("SyntaxError: " + message + "\n");
    int pos = message.indexOf("line");
    if (pos > 0) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(message);
        if (m.find(pos)) {
            int lineNo = Integer.parseInt(message.substring(m.start(), m.end()));
            String[] lines = query.split("\n");
            if (lineNo > lines.length) {
                errorMessage.append("===> &ltBLANK LINE&gt \n");
            } else {
                String line = lines[lineNo - 1];
                errorMessage.append("==> " + line);
            }/*  w  w  w.  j a v  a2  s  .c  o  m*/
        }
    }
    return errorMessage.toString();
}

From source file:com.screenslicer.common.HtmlCoder.java

private static String decode(String string, boolean isAttributeValue) {
    try {//from ww w.  j av a2s . c o m
        if (CommonUtil.isEmpty(string)) {
            return "";
        }
        Matcher matcher = regexDecode.matcher(string);
        StringBuilder builder = new StringBuilder();
        int prevEnd = 0;
        while (matcher.find()) {
            builder.append(string.substring(prevEnd, matcher.start()));
            prevEnd = matcher.end();
            int codePoint;
            String hexDigits;
            String reference;
            String next;
            if (!CommonUtil.isEmpty(matcher.group(1))) {
                // Decode decimal escapes, e.g. `&#119558;`.
                codePoint = Integer.parseInt(matcher.group(1));
                builder.append(codePointToSymbol(codePoint));
                continue;
            }
            if (!CommonUtil.isEmpty(matcher.group(3))) {
                // Decode hexadecimal escapes, e.g. `&#x1D306;`.
                hexDigits = matcher.group(3);
                codePoint = Integer.parseInt(hexDigits, 16);
                builder.append(codePointToSymbol(codePoint));
                continue;
            }
            if (!CommonUtil.isEmpty(matcher.group(5))) {
                // Decode named character references with trailing `;`, e.g. `&copy;`.
                reference = matcher.group(5);
                if (decodeMap.containsKey(reference)) {
                    builder.append(decodeMap.get(reference));
                    continue;
                } else {
                    // Ambiguous ampersand. https://mths.be/notes/ambiguous-ampersands
                    builder.append(matcher.group(0));
                    continue;
                }
            }
            // If were still here, its a legacy reference for sure. No need for an
            // extra `if` check.
            // Decode named character references without trailing `;`, e.g. `&amp`
            // This is only a parse error if it gets converted to `&`, or if it is
            // followed by `=` in an attribute context.
            reference = matcher.group(6);
            next = matcher.group(7);
            if (!CommonUtil.isEmpty(next) && isAttributeValue) {
                builder.append(matcher.group(0));
                continue;
            } else if (decodeMapLegacy.containsKey(reference)) {
                builder.append(decodeMapLegacy.get(reference) + (CommonUtil.isEmpty(next) ? "" : next));
                continue;
            }
        }
        builder.append(string.substring(prevEnd, string.length()));
        return builder.toString();
    } catch (Throwable t) {
        Log.exception(t);
        return string;
    }
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

public static Mail createMailByTemplateStream(InputStream in, Map<String, String> replaced) throws IOException {
    Mail mail = new Mail();
    InputStreamReader reader = new InputStreamReader(in, "utf-8");
    char[] buffer = new char[1024];
    StringBuilder builder = new StringBuilder();
    while (reader.read(buffer) != -1)
        builder.append(buffer);/*from  w w  w. j a  va  2 s  .c  o m*/
    String mailBody = builder.toString();
    builder.setLength(0);
    Pattern pattern = Pattern.compile("<%\\s*(.+?)\\s*%>", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(mailBody);
    int scanPos = 0;
    while (matcher.find()) {
        builder.append(mailBody.substring(scanPos, matcher.start()));
        scanPos = matcher.end();
        String key = matcher.group(1);
        if (replaced != null) {
            String value = replaced.get(key);
            if (value != null) {
                builder.append(value);
            }
        }
    }
    builder.append(mailBody.substring(scanPos, mailBody.length()));
    mail.htmlBody = builder.toString();
    pattern = Pattern.compile("<title>(.*)</title>",
            Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(mail.htmlBody);
    if (matcher.find()) {
        mail.subject = matcher.group(1);
    }
    return mail;
}

From source file:com.github.thorqin.webapi.mail.MailService.java

public static Mail createHtmlMailFromTemplate(String templatePath, Map<String, String> replaced) {
    Mail mail = new Mail();
    try (InputStream in = MailService.class.getClassLoader().getResourceAsStream(templatePath)) {
        InputStreamReader reader = new InputStreamReader(in, "utf-8");
        char[] buffer = new char[1024];
        StringBuilder builder = new StringBuilder();
        while (reader.read(buffer) != -1)
            builder.append(buffer);/*  w ww  .ja  va 2 s  . c om*/
        String mailBody = builder.toString();
        builder.setLength(0);
        Pattern pattern = Pattern.compile("<%\\s*(.+?)\\s*%>", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(mailBody);
        int scanPos = 0;
        while (matcher.find()) {
            builder.append(mailBody.substring(scanPos, matcher.start()));
            scanPos = matcher.end();
            String key = matcher.group(1);
            if (replaced != null) {
                String value = replaced.get(key);
                if (value != null) {
                    builder.append(value);
                }
            }
        }
        builder.append(mailBody.substring(scanPos, mailBody.length()));
        mail.htmlBody = builder.toString();
        pattern = Pattern.compile("<title>(.*)</title>",
                Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(mail.htmlBody);
        if (matcher.find()) {
            mail.subject = matcher.group(1);
        }
    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Create mail from template error: {0}, {1}",
                new Object[] { templatePath, ex });
    }
    return mail;
}