Search in sources :

Example 61 with Pattern

use of java.util.regex.Pattern in project simplefacebook by androidquery.

the class PatternUtility method transform.

public static String transform(String html, String match, Transformer tran) {
    Pattern p = Pattern.compile(match);
    Matcher m = p.matcher(html);
    StringBuffer sb = new StringBuffer();
    boolean found = false;
    while (m.find()) {
        found = true;
        String g = m.group();
        try {
            g = tran.transform(g);
        } catch (Exception e) {
            AQUtility.debug(e);
        }
        m.appendReplacement(sb, g);
    }
    if (!found) {
        return html;
    }
    m.appendTail(sb);
    return sb.toString();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher)

Example 62 with Pattern

use of java.util.regex.Pattern in project simplefacebook by androidquery.

the class PatternUtility method toAttributes.

public static Map<String, String> toAttributes(String tag) {
    Map<String, String> result = new HashMap<String, String>();
    if (tag == null)
        return result;
    String reg = "[\\w]+[\\s]*=[\\s]*\"[^\"]+\"";
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(tag);
    while (m.find()) {
        String g = m.group();
        int index = g.indexOf('=');
        if (index > 0) {
            String key = g.substring(0, index).trim();
            String value = g.substring(index + 1, g.length()).replace("\"", "").trim();
            result.put(key, value);
        }
    }
    return result;
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher)

Example 63 with Pattern

use of java.util.regex.Pattern in project androrm by androrm.

the class DateField method fromString.

/**
	 * Constructs a {@link Date} object from the given string. <br />
	 * The String must be in the format: YYYY-MM-DDTHH:MM:SS.
	 * 
	 * @param date	String representing the date.
	 */
public void fromString(String date) {
    Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})");
    if (date != null) {
        Matcher matcher = pattern.matcher(date);
        if (matcher.matches()) {
            int year = Integer.valueOf(matcher.group(1));
            int month = Integer.valueOf(matcher.group(2)) - 1;
            int day = Integer.valueOf(matcher.group(3));
            int hour = Integer.valueOf(matcher.group(4));
            int minute = Integer.valueOf(matcher.group(5));
            int second = Integer.valueOf(matcher.group(6));
            GregorianCalendar cal = new GregorianCalendar(year, month, day, hour, minute, second);
            mValue = cal.getTime();
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) GregorianCalendar(java.util.GregorianCalendar)

Example 64 with Pattern

use of java.util.regex.Pattern in project grails-core by grails.

the class RegexUrlMapping method convertToRegex.

/**
     * Converts a Grails URL provides via the UrlMappingData interface to a regular expression.
     *
     * @param url The URL to convert
     * @return A regex Pattern objet
     */
protected Pattern convertToRegex(String url) {
    Pattern regex;
    String pattern = null;
    try {
        // Escape any characters that have special meaning in regular expressions,
        // such as '.' and '+'.
        pattern = url.replace(".", "\\.");
        pattern = pattern.replace("+", "\\+");
        int lastSlash = pattern.lastIndexOf('/');
        String urlRoot = lastSlash > -1 ? pattern.substring(0, lastSlash) : pattern;
        String urlEnd = lastSlash > -1 ? pattern.substring(lastSlash, pattern.length()) : "";
        // Now replace "*" with "[^/]" and "**" with ".*".
        pattern = "^" + urlRoot.replace("(\\.(*))", "(\\.[^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+?$2").replaceAll("([^\\*])\\*$", "$1[^/]+?").replaceAll("\\*\\*", ".*");
        if ("/(*)(\\.(*))".equals(urlEnd)) {
            // shortcut this common special case which will
            // happen any time a URL mapping ends with a pattern like
            // /$someVariable(.$someExtension)
            pattern += "/([^/]+)\\.([^/.]+)?";
        } else {
            pattern += urlEnd.replace("(\\.(*))", "(\\.[^/]+)?").replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+?$2").replaceAll("([^\\*])\\*$", "$1[^/]+?").replaceAll("\\*\\*", ".*").replaceAll("\\(\\[\\^\\/\\]\\+\\)\\\\\\.", "([^/.]+?)\\\\.").replaceAll("\\(\\[\\^\\/\\]\\+\\)\\?\\\\\\.", "([^/.]+?)\\?\\\\.");
        }
        pattern += "/??$";
        regex = Pattern.compile(pattern);
    } catch (PatternSyntaxException pse) {
        throw new UrlMappingException("Error evaluating mapping for pattern [" + pattern + "] from Grails URL mappings: " + pse.getMessage(), pse);
    }
    return regex;
}
Also used : UrlMappingException(grails.web.mapping.exceptions.UrlMappingException) Pattern(java.util.regex.Pattern) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 65 with Pattern

use of java.util.regex.Pattern in project grails-core by grails.

the class RegexUrlMapping method parse.

private void parse(UrlMappingData data, ConstrainedProperty[] constraints) {
    Assert.notNull(data, "Argument [data] cannot be null");
    String[] urls = data.getLogicalUrls();
    urlData = data;
    patterns = new Pattern[urls.length];
    for (int i = 0; i < urls.length; i++) {
        String url = urls[i];
        Integer slashCount = org.springframework.util.StringUtils.countOccurrencesOf(url, "/");
        List<Pattern> tokenCountPatterns = patternByTokenCount.get(slashCount);
        if (tokenCountPatterns == null) {
            tokenCountPatterns = new ArrayList<>();
            patternByTokenCount.put(slashCount, tokenCountPatterns);
        }
        Pattern pattern = convertToRegex(url);
        if (pattern == null) {
            throw new IllegalStateException("Cannot use null pattern in regular expression mapping for url [" + data.getUrlPattern() + "]");
        }
        tokenCountPatterns.add(pattern);
        this.patterns[i] = pattern;
    }
    if (constraints != null) {
        String[] tokens = data.getTokens();
        int pos = 0;
        int currentToken = 0;
        int tokensLength = tokens.length - 1;
        int constraintUpperBound = constraints.length;
        if (data.hasOptionalExtension()) {
            constraintUpperBound--;
            setNullable(constraints[constraintUpperBound]);
        }
        for (int i = 0; i < constraintUpperBound; i++) {
            ConstrainedProperty constraint = constraints[i];
            if (currentToken > tokensLength)
                break;
            String token = tokens[currentToken];
            int shiftLength = 3;
            pos = token.indexOf(CAPTURED_WILDCARD, pos);
            while (pos == -1) {
                boolean isLastToken = currentToken == tokensLength - 1;
                if (currentToken < tokensLength) {
                    token = tokens[++currentToken];
                    // special handling for last token to deal with optional extension
                    if (isLastToken) {
                        if (token.startsWith(CAPTURED_WILDCARD + '?')) {
                            setNullable(constraint);
                        }
                        if (token.endsWith(OPTIONAL_EXTENSION_WILDCARD + '?')) {
                            setNullable(constraints[constraints.length - 1]);
                        }
                    } else {
                        pos = token.indexOf(CAPTURED_WILDCARD, pos);
                    }
                } else {
                    break;
                }
            }
            if (pos != -1 && pos + shiftLength < token.length() && token.charAt(pos + shiftLength) == '?') {
                setNullable(constraint);
            }
            // Move on to the next place-holder.
            pos += shiftLength;
            if (token.indexOf(CAPTURED_WILDCARD, pos) == -1) {
                currentToken++;
                pos = 0;
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ConstrainedProperty(grails.gorm.validation.ConstrainedProperty)

Aggregations

Pattern (java.util.regex.Pattern)3181 Matcher (java.util.regex.Matcher)2116 ArrayList (java.util.ArrayList)387 IOException (java.io.IOException)247 Test (org.junit.Test)238 File (java.io.File)193 HashMap (java.util.HashMap)163 BufferedReader (java.io.BufferedReader)127 Field (java.lang.reflect.Field)119 PatternSyntaxException (java.util.regex.PatternSyntaxException)119 Map (java.util.Map)110 List (java.util.List)93 HashSet (java.util.HashSet)79 InputStreamReader (java.io.InputStreamReader)67 InputStream (java.io.InputStream)43 FileReader (java.io.FileReader)41 FileInputStream (java.io.FileInputStream)40 URL (java.net.URL)35 SmallTest (android.test.suitebuilder.annotation.SmallTest)31 LinkedHashMap (java.util.LinkedHashMap)31