List of usage examples for java.util.regex Matcher start
public int start()
From source file:hudson.Util.java
/** * Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>. * * <p>/*from w w w. j a v a2s. c o m*/ * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.) */ public static String replaceMacro(String s, VariableResolver<String> resolver) { if (s == null) { return null; } int idx = 0; while (true) { Matcher m = VARIABLE.matcher(s); if (!m.find(idx)) return s; String key = m.group().substring(1); // escape the dollar sign or get the key to resolve String value; if (key.charAt(0) == '$') { value = "$"; } else { if (key.charAt(0) == '{') key = key.substring(1, key.length() - 1); value = resolver.resolve(key); } if (value == null) idx = m.end(); // skip this else { s = s.substring(0, m.start()) + value + s.substring(m.end()); idx = m.start() + value.length(); } } }
From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java
@Override public void addJoinAndWhere(String join, String where) { Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer); String alias = findAlias(entityMatcher); int insertPos = buffer.length(); Matcher whereMatcher = WHERE_PATTERN.matcher(buffer); if (whereMatcher.find(entityMatcher.end())) { insertPos = whereMatcher.start() - 1; } else {/*from w w w . java 2 s. c o m*/ Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer); if (lastClauseMatcher.find(entityMatcher.end())) insertPos = lastClauseMatcher.start() - 1; } if (!StringUtils.isBlank(join)) { buffer.insert(insertPos, " "); insertPos++; buffer.insert(insertPos, join); Matcher paramMatcher = PARAM_PATTERN.matcher(join); while (paramMatcher.find()) { addedParams.add(paramMatcher.group(1)); } } if (!StringUtils.isBlank(where)) { insertPos = buffer.length(); Matcher lastClauseMatcher = LAST_CLAUSE_PATTERN.matcher(buffer); if (lastClauseMatcher.find(entityMatcher.end())) insertPos = lastClauseMatcher.start() - 1; StringBuilder sb = new StringBuilder(); whereMatcher = WHERE_PATTERN.matcher(buffer); int whereEnd = -1; boolean needOpenBracket = false; if (whereMatcher.find(entityMatcher.end())) { whereEnd = whereMatcher.end(); Matcher orMatcher = OR_PATTERN.matcher(buffer); orMatcher.region(whereEnd + 1, insertPos); if (orMatcher.find()) { // surround with brackets if there is OR inside WHERE sb.append(")"); needOpenBracket = true; } sb.append(" and "); } else { sb.append(" where "); } sb.append("(").append(where).append(")"); if (needOpenBracket) { buffer.insert(whereEnd + 1, "("); insertPos++; } buffer.insert(insertPos, sb); Matcher paramMatcher = PARAM_PATTERN.matcher(where); while (paramMatcher.find()) { addedParams.add(paramMatcher.group(1)); } } // replace ALIAS_PLACEHOLDER int idx; while ((idx = buffer.indexOf(ALIAS_PLACEHOLDER)) >= 0) { buffer.replace(idx, idx + ALIAS_PLACEHOLDER.length(), alias); } }
From source file:mobi.jenkinsci.server.core.net.ProxyUtil.java
private String resolveCss(final String userAgent, final String pluginName, final String url, final String resultString) throws IOException { log.debug("Resolving CSS for URL " + url); final StringBuilder outString = new StringBuilder(); int currPos = 0; final Pattern cssLinkPattern = Pattern.compile("<link" + "[^>]*" + "rel=[\"']stylesheet[\"']" + "[^>]*" + "href=[\"']([^>\"']*)[\"']" + "[^>]*" + "/>", Pattern.DOTALL); final Matcher matcher = cssLinkPattern.matcher(resultString); while (matcher.find(currPos)) { final int start = matcher.start(); final int end = matcher.end(); outString.append(resultString.substring(currPos, start)); final String cssUrl = matcher.group(1); String cssText = retrieveCss(userAgent, pluginName, url, cssUrl); cssText = resolveImages(userAgent, pluginName, Pattern.compile(CSS_BACKGROUND_IMAGE_PATTERN, Pattern.DOTALL), 2, getBasePathUrl(resolveRelativeUrl(url, cssUrl)), cssText); outString.append(cssText);/*from w w w . j av a 2s.c o m*/ currPos = end; } outString.append(resultString.substring(currPos)); log.debug(outString.length() + " CSS chars included for URL " + url); return outString.toString(); }
From source file:com.arcao.geocaching.api.data.coordinates.CoordinatesParser.java
protected static ParseResult parse(String coordinate, CoordinateType coordinateType) throws ParseException { Pattern pattern;/*from www. jav a 2 s .c o m*/ switch (coordinateType) { case LAT_UNSAFE: pattern = LATITUDE_PATTERN_UNSAFE; break; case LON_UNSAFE: pattern = LONGITUDE_PATTERN_UNSAFE; break; case LON: pattern = LONGITUDE_PATTERN; break; case LAT: default: pattern = LATITUDE_PATTERN; break; } final Matcher matcher = pattern.matcher(coordinate); if (matcher.find()) { double sign = matcher.group(1).equalsIgnoreCase("S") || matcher.group(1).equalsIgnoreCase("W") ? -1.0 : 1.0; double degree = Double.parseDouble(matcher.group(2)); if (degree < 0) { sign = -1; degree = Math.abs(degree); } double minutes = 0.0; double seconds = 0.0; if (matcher.group(3) != null) { minutes = Double.parseDouble(matcher.group(3)); if (matcher.group(4) != null) { seconds = Double.parseDouble("0." + matcher.group(4)) * 60.0; } else if (matcher.group(5) != null) { seconds = Double.parseDouble(matcher.group(5).replace(",", ".")); } } double result = sign * (degree + minutes / 60.0 + seconds / 3600.0); // normalize result switch (coordinateType) { case LON_UNSAFE: case LON: result = normalize(result, -180, 180); break; case LAT_UNSAFE: case LAT: default: result = normalize(result, -90, 90); break; } return new ParseResult(result, matcher.start(), matcher.group().length()); } else { // Nothing found with "N 52...", try to match string as decimaldegree try { final String[] items = StringUtils.split(coordinate.trim()); if (items.length > 0) { final int index = (coordinateType == CoordinateType.LON ? items.length - 1 : 0); final int pos = (coordinateType == CoordinateType.LON ? coordinate.lastIndexOf(items[index]) : coordinate.indexOf(items[index])); return new ParseResult(Double.parseDouble(items[index]), pos, items[index].length()); } } catch (NumberFormatException e) { logger.error(e.getMessage(), e); } } throw new ParseException("Could not parse coordinate: \"" + coordinate + "\"", 0); }
From source file:com.jaspersoft.jasperserver.war.cascade.token.FilterCore.java
private Parameter nextParameter(String queryString, int start) { if (start < 0 && start > queryString.length() - 1) return null; Matcher m = ParameterTypes.pattern.matcher(queryString); Parameter p = null;// ww w . j a v a2 s . co m if (m.find(start)) { p = createParameter(m.group(1), m.group(2)); if (p != null) { p.setStartPosition(m.start()); p.setEndPosition(m.end()); } } return p; }
From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java
@Override protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata, boolean parsed, boolean partialContent) { int flags = Pattern.DOTALL | Pattern.UNICODE_CASE; if (!caseSensitive) { flags = flags | Pattern.CASE_INSENSITIVE; }//from ww w .j a v a 2 s . c o m for (Pair<String, String> pair : stripPairs) { List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>(); Pattern leftPattern = Pattern.compile(pair.getLeft(), flags); Matcher leftMatch = leftPattern.matcher(content); while (leftMatch.find()) { Pattern rightPattern = Pattern.compile(pair.getRight(), flags); Matcher rightMatch = rightPattern.matcher(content); if (rightMatch.find(leftMatch.end())) { if (inclusive) { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end())); } else { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start())); } } else { break; } } for (int i = matches.size() - 1; i >= 0; i--) { Pair<Integer, Integer> matchPair = matches.get(i); content.delete(matchPair.getLeft(), matchPair.getRight()); } } }
From source file:com.digitalpebble.stormcrawler.filtering.basic.BasicURLNormalizer.java
/** * Remove % encoding from path segment in URL for characters which should be * unescaped according to <a//from ww w . j a va 2s . co m * href="https://tools.ietf.org/html/rfc3986#section-2.2">RFC3986</a>. */ private String unescapePath(String path) { StringBuilder sb = new StringBuilder(); Matcher matcher = unescapeRulePattern.matcher(path); int end = -1; int letter; // Traverse over all encoded groups while (matcher.find()) { // Append everything up to this group sb.append(path.substring(end + 1, matcher.start())); // Get the integer representation of this hexadecimal encoded // character letter = Integer.valueOf(matcher.group().substring(1), 16); if (letter < 128 && unescapedCharacters[letter]) { // character should be unescaped in URLs sb.append(new Character((char) letter)); } else { // Append the encoded character as uppercase sb.append(matcher.group().toUpperCase(Locale.ROOT)); } end = matcher.start() + 2; } letter = path.length(); // Append the rest if there's anything if (end <= letter - 1) { sb.append(path.substring(end + 1, letter)); } // Ok! return sb.toString(); }
From source file:meff.Function.java
private Map<String, String> compile() { class Compiler { private Map<String, StringBuilder> functions; private String currentFunctionName; private StringBuilder currentFunction; Compiler(String functionName) { functions = new HashMap<>(); currentFunctionName = functionName; currentFunction = new StringBuilder(); functions.put(currentFunctionName, currentFunction); }//from w w w .j a v a 2 s.c om void compileLine(StringBuilder line) { // Manage score value features { Matcher m = Pattern.compile("(score_\\w+)(>=|>|<=|<|==)(-?\\d+)").matcher(line); while (m.find()) { int offset = m.start(); String beginning = m.group(1); String operator = m.group(2); String end = m.group(3); StringBuilder newScore = new StringBuilder(); switch (operator) { case ">=": newScore.append(beginning).append("_min=").append(end); break; case ">": newScore.append(beginning).append("_min=").append(Integer.parseInt(end) + 1); break; case "<=": newScore.append(beginning).append("=").append(end); break; case "<": newScore.append(beginning).append("=").append(Integer.parseInt(end) - 1); break; case "==": newScore.append(beginning).append("_min=").append(end).append(",").append(beginning) .append("=").append(end); break; } line.replace(offset, offset + m.group().length(), newScore.toString()); m.reset(); // Need to reset the matcher, so it updates the length of the text } } currentFunction.append(line).append("\n"); } Map<String, String> getOutput() { Map<String, String> outputMap = new HashMap<>(functions.size()); for (Map.Entry<String, StringBuilder> entry : functions.entrySet()) { outputMap.put(entry.getKey() + ".mcfunction", entry.getValue().toString()); } return outputMap; } } Compiler compiler = new Compiler(getName()); boolean comment = false; StringBuilder sb = new StringBuilder(); for (String line : data.lines) { line = line.trim(); if (line.startsWith("#") || line.startsWith("//")) { continue; } if (line.isEmpty()) { continue; } int si = 0; // start index int bci = -1; // block comment index int bcei = -1; // block comment end index int prevBci = -1; int prevBcei = -1; while ((!comment && (bci = line.indexOf("/*", si)) > -1) || (comment && (bcei = line.indexOf("*/", si)) > -1)) { if (comment) { if (line.charAt(bcei - 1) == '\\') { si = bcei + 2; bcei = prevBcei; continue; } comment = false; si = bcei + 2; } else { if (line.charAt(bci - 1) == '\\') { sb.append(line.substring(si, bci - 1)).append("/*"); si = bci + 2; bci = prevBci; continue; } sb.append(line.substring(si, bci)); comment = true; si = bci + 2; } prevBci = bci; prevBcei = bcei; } if (comment) { continue; } if (line.endsWith("\\")) { line = line.substring(si, line.length() - 1); sb.append(line); } else { sb.append(line.substring(si)); compiler.compileLine(sb); sb.delete(0, sb.length()); } } return compiler.getOutput(); }
From source file:net.sf.jabref.importer.fetcher.GoogleScholarFetcher.java
private String getCitationsFromUrl(String urlQuery, Map<String, JLabel> ids) throws IOException { String cont = new URLDownload(urlQuery).downloadToString(Globals.prefs.getDefaultEncoding()); Matcher m = GoogleScholarFetcher.BIBTEX_LINK_PATTERN.matcher(cont); int lastRegionStart = 0; while (m.find()) { String link = m.group(1).replace("&", "&"); String pText;/*w w w.j av a2 s. c o m*/ String part = cont.substring(lastRegionStart, m.start()); Matcher titleS = GoogleScholarFetcher.TITLE_START_PATTERN.matcher(part); Matcher titleE = GoogleScholarFetcher.TITLE_END_PATTERN.matcher(part); boolean fS = titleS.find(); boolean fE = titleE.find(); if (fS && fE) { if (titleS.end() < titleE.start()) { pText = part.substring(titleS.end(), titleE.start()); } else { pText = part; } } else { pText = link; } pText = pText.replace("[PDF]", ""); JLabel preview = new JLabel("<html>" + pText + "</html>"); ids.put(link, preview); // See if we can extract the link Google Scholar puts on the entry's title. // That will be set as "url" for the entry if downloaded: Matcher linkMatcher = GoogleScholarFetcher.LINK_PATTERN.matcher(pText); if (linkMatcher.find()) { entryLinks.put(link, linkMatcher.group(1)); } lastRegionStart = m.end(); } /*m = NEXT_PAGE_PATTERN.matcher(cont); if (m.find()) { System.out.println("NEXT: "+URL_START+m.group(1).replace("&", "&")); return URL_START+m.group(1).replace("&", "&"); } else*/ return null; }
From source file:hudson.plugins.simpleupdatesite.HPI.java
public List<Developer> getDevelopers(Attributes attributes) throws IOException { String devs = attributes.getValue("Plugin-Developers"); if (devs == null || devs.trim().length() == 0) { return Collections.emptyList(); }/*w w w . ja va2 s .c o m*/ List<Developer> result = new ArrayList<Developer>(); Matcher matcher = this.developersPattern.matcher(devs); int totalMatched = 0; while (matcher.find()) { result.add(new Developer(StringUtils.trimToEmpty(matcher.group(1)), StringUtils.trimToEmpty(matcher.group(2)), StringUtils.trimToEmpty(matcher.group(3)))); totalMatched += matcher.end() - matcher.start(); } if (totalMatched < devs.length()) { // ignore and move on System.err.println("Unparsable developer info: '" + devs.substring(totalMatched) + "'"); } return result; }