List of usage examples for java.util.regex Matcher start
public int start()
From source file:com.fsck.k9.helper.Utility.java
/** * Extract the 'original' subject value, by ignoring leading * response/forward marker and '[XX]' formatted tags (as many mailing-list * softwares do).//from w ww . ja v a 2 s . co m * * <p> * Result is also trimmed. * </p> * * @param subject * Never <code>null</code>. * @return Never <code>null</code>. */ public static String stripSubject(final String subject) { int lastPrefix = 0; final Matcher tagMatcher = TAG_PATTERN.matcher(subject); String tag = null; // whether tag stripping logic should be active boolean tagPresent = false; // whether the last action stripped a tag boolean tagStripped = false; if (tagMatcher.find(0)) { tagPresent = true; if (tagMatcher.start() == 0) { // found at beginning of subject, considering it an actual tag tag = tagMatcher.group(); // now need to find response marker after that tag lastPrefix = tagMatcher.end(); tagStripped = true; } } final Matcher matcher = RESPONSE_PATTERN.matcher(subject); // while: // - lastPrefix is within the bounds // - response marker found at lastPrefix position // (to make sure we don't catch response markers that are part of // the actual subject) while (lastPrefix < subject.length() - 1 && matcher.find(lastPrefix) && matcher.start() == lastPrefix && (!tagPresent || tag == null || subject.regionMatches(matcher.end(), tag, 0, tag.length()))) { lastPrefix = matcher.end(); if (tagPresent) { tagStripped = false; if (tag == null) { // attempt to find tag if (tagMatcher.start() == lastPrefix) { tag = tagMatcher.group(); lastPrefix += tag.length(); tagStripped = true; } } else if (lastPrefix < subject.length() - 1 && subject.startsWith(tag, lastPrefix)) { // Re: [foo] Re: [foo] blah blah blah // ^ ^ // ^ ^ // ^ new position // ^ // initial position lastPrefix += tag.length(); tagStripped = true; } } } // Null pointer check is to make the static analysis component of Eclipse happy. if (tagStripped && (tag != null)) { // restore the last tag lastPrefix -= tag.length(); } if (lastPrefix > -1 && lastPrefix < subject.length() - 1) { return subject.substring(lastPrefix).trim(); } else { return subject.trim(); } }
From source file:io.github.lucaseasedup.logit.config.PredefinedConfiguration.java
/** * Converts a hyphenated path (example-path.secret-setting) * to a camelCase path (examplePath.secretSetting). * // ww w. ja v a 2s . c om * @param hyphenatedPath the hyphenated path. * * @return the camelCase equivalent of the provided hyphenated path. */ public static String getCamelCasePath(String hyphenatedPath) { Matcher matcher = HYPHENATED_PATH_PATTERN.matcher(hyphenatedPath); StringBuilder sb = new StringBuilder(); int last = 0; while (matcher.find()) { sb.append(hyphenatedPath.substring(last, matcher.start())); sb.append(matcher.group(1).toUpperCase()); last = matcher.end(); } sb.append(hyphenatedPath.substring(last)); return sb.toString(); }
From source file:com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck.java
/** Tries to find better matching regular expression: * longer matching substring wins; in case of the same length, * lower position of matching substring wins. * @param importPath/* w w w. ja va 2s . co m*/ * Full import identifier * @param group * Import group we are trying to assign the import * @param regExp * Regular expression for import group * @param currentBestMatch * object with currently best match * @return better match (if found) or the same (currentBestMatch) */ private static RuleMatchForImport findBetterPatternMatch(String importPath, String group, Pattern regExp, RuleMatchForImport currentBestMatch) { RuleMatchForImport betterMatchCandidate = currentBestMatch; final Matcher matcher = regExp.matcher(importPath); while (matcher.find()) { final int length = matcher.end() - matcher.start(); if (length > betterMatchCandidate.matchLength || length == betterMatchCandidate.matchLength && matcher.start() < betterMatchCandidate.matchPosition) { betterMatchCandidate = new RuleMatchForImport(group, length, matcher.start()); } } return betterMatchCandidate; }
From source file:com.datatorrent.stram.client.StramClientUtils.java
public static void evalProperties(Properties target, Configuration vars) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); Pattern substitutionPattern = Pattern.compile("\\$\\{(.+?)\\}"); Pattern evalPattern = Pattern.compile("\\{% (.+?) %\\}"); try {/*w w w.j av a 2 s .c om*/ engine.eval("var _prop = {}"); for (Map.Entry<String, String> entry : vars) { String evalString = String.format("_prop[\"%s\"] = \"%s\"", StringEscapeUtils.escapeJava(entry.getKey()), StringEscapeUtils.escapeJava(entry.getValue())); engine.eval(evalString); } } catch (ScriptException ex) { LOG.warn("Javascript error: {}", ex.getMessage()); } for (Map.Entry<Object, Object> entry : target.entrySet()) { String value = entry.getValue().toString(); Matcher matcher = substitutionPattern.matcher(value); if (matcher.find()) { StringBuilder newValue = new StringBuilder(); int cursor = 0; do { newValue.append(value.substring(cursor, matcher.start())); String subst = vars.get(matcher.group(1)); if (subst != null) { newValue.append(subst); } cursor = matcher.end(); } while (matcher.find()); newValue.append(value.substring(cursor)); target.put(entry.getKey(), newValue.toString()); } matcher = evalPattern.matcher(value); if (matcher.find()) { StringBuilder newValue = new StringBuilder(); int cursor = 0; do { newValue.append(value.substring(cursor, matcher.start())); try { Object result = engine.eval(matcher.group(1)); String eval = result.toString(); if (eval != null) { newValue.append(eval); } } catch (ScriptException ex) { LOG.warn("JavaScript exception {}", ex.getMessage()); } cursor = matcher.end(); } while (matcher.find()); newValue.append(value.substring(cursor)); target.put(entry.getKey(), newValue.toString()); } } }
From source file:ca.sqlpower.object.SPVariableHelper.java
/** * Helper method that takes a connection and a SQL statement which includes variable and * converts all that in a nifty prepared statement ready for execution, on time for Christmas. * @param connection A connection object to use in order to generate the prepared statement. * @param sql A SQL string which might include variables. * @param variableHelper A {@link SPVariableHelper} object to resolve the variables. * @return A {@link PreparedStatement} object ready for execution. * @throws SQLException Might get thrown if we cannot generate a {@link PreparedStatement} with the supplied connection. *//* w w w. ja v a2s . c om*/ public static PreparedStatement substituteForDb(Connection connection, String sql, SPVariableHelper variableHelper) throws SQLException { // Make sure that the registry is ready. SPResolverRegistry.init(variableHelper.getContextSource()); StringBuilder text = new StringBuilder(); Matcher matcher = varPattern.matcher(sql); List<Object> vars = new LinkedList<Object>(); // First, change all vars to '?' markers. int currentIndex = 0; while (!matcher.hitEnd()) { if (matcher.find()) { String variableName = matcher.group(1); if (variableName.equals("$")) { vars.add("$"); } else { vars.add(variableHelper.resolve(variableName)); } text.append(sql.substring(currentIndex, matcher.start())); text.append("?"); currentIndex = matcher.end(); } } text.append(sql.substring(currentIndex)); // Now generate a prepared statement and inject it's variables. PreparedStatement ps = connection.prepareStatement(text.toString()); for (int i = 0; i < vars.size(); i++) { ps.setObject(i + 1, vars.get(i)); } return ps; }
From source file:ca.sqlpower.object.SPVariableHelper.java
/** * Helper method that takes a connection and a MDX statement which includes variable and * converts all that in a nifty prepared statement ready for execution, on time for Christmas. * @param connection A connection object to use in order to generate the prepared statement. * @param sql A MDX string which might include variables. * @param variableHelper A {@link SPVariableHelper} object to resolve the variables. * @return A {@link PreparedStatement} object ready for execution. * @throws SQLException Might get thrown if we cannot generate a {@link PreparedStatement} with the supplied connection. *///from w ww . j a v a 2 s .co m public static PreparedOlapStatement substituteForDb(OlapConnection connection, String mdxQuery, SPVariableHelper variableHelper) throws SQLException { // Make sure that the registry is ready. SPResolverRegistry.init(variableHelper.getContextSource()); StringBuilder text = new StringBuilder(); Matcher matcher = varPattern.matcher(mdxQuery); List<Object> vars = new LinkedList<Object>(); // First, change all vars to '?' markers. int currentIndex = 0; while (!matcher.hitEnd()) { if (matcher.find()) { String variableName = matcher.group(1); if (variableName.equals("$")) { vars.add("$"); } else { vars.add(variableHelper.resolve(variableName)); } text.append(mdxQuery.substring(currentIndex, matcher.start())); text.append("?"); currentIndex = matcher.end(); } } text.append(mdxQuery.substring(currentIndex)); // Now generate a prepared statement and inject it's variables. PreparedOlapStatement ps = connection.prepareOlapStatement(text.toString()); for (int i = 0; i < vars.size(); i++) { ps.setObject(i + 1, vars.get(i)); } return ps; }
From source file:com.gzj.tulip.jade.statement.cached.CachedStatement.java
/** * ? KEY :name, :name.property ???/*from ww w . jav a 2 s .com*/ * * @param key - ? KEY * @param parameters - ? * * @return KEY * @author in355hz@gmail.com */ private static String buildKey(String key, Map<String, Object> parameters) { // ?? :name ?? Matcher matcher = PATTERN.matcher(key); if (matcher.find()) { StringBuilder builder = new StringBuilder(); int index = 0; do { // ?????? final String name = matcher.group(1).trim(); Object value = null; // ? a.b.c ?? int find = name.indexOf('.'); if (find >= 0) { // BeanWrapper ? Object bean = parameters.get(name.substring(0, find)); if (bean != null) { value = new BeanWrapperImpl(bean).getPropertyValue(name.substring(find + 1)); } } else { // ?? value = parameters.get(name); } // ? builder.append(key.substring(index, matcher.start())); builder.append(value); index = matcher.end(); } while (matcher.find()); // ? builder.append(key.substring(index)); return builder.toString(); } return key; }
From source file:com.tdclighthouse.commons.simpleform.validation.validator.item.PatternMatchValidator.java
private boolean performValidation(FormItem item, String param) { boolean result = true; item.setErrorMessage(null);/*from w w w. ja v a 2 s . co m*/ String value = item.getValue(); if (!StringUtils.isBlank(value)) { value = value.trim(); Pattern pattern = Pattern.compile(param); Matcher matcher = pattern.matcher(value); if (matcher.find()) { result = ((matcher.start() == 0) && (matcher.end() == value.length())); } else { result = false; item.setErrorMessage(getMessage()); } } return result; }
From source file:net.duckling.falcon.api.mq.impl.SimpleStringMatch.java
public String routingMatch(Map<String, String> regMap, String value) { if (StringUtils.isEmpty(value)) { return ""; }/*from ww w .java 2 s. c om*/ if (regMap.keySet().contains(value)) { return value; } String matchedReg = null; for (Map.Entry<String, String> entry : regMap.entrySet()) { Pattern m = Pattern.compile(entry.getValue()); Matcher matcher = m.matcher(value); while (matcher.find()) { if (matcher.start() == 0 && (matcher.end() == value.length())) { matchedReg = entry.getKey(); return matchedReg; } } } return null; }
From source file:ca.sqlpower.object.SPVariableHelper.java
/** * Substitutes any number of variable references in the given string, returning * the resultant string with all variable references replaced by the corresponding * variable values.//from w ww. ja va 2 s . c om * * @param textWithVars * @param variableContext * @return */ public static String substitute(String textWithVars, SPVariableHelper variableHelper) { logger.debug("Performing variable substitution on " + textWithVars); // Make sure that the registry is ready. SPResolverRegistry.init(variableHelper.getContextSource()); StringBuilder text = new StringBuilder(); Matcher matcher = varPattern.matcher(textWithVars); int currentIndex = 0; while (!matcher.hitEnd()) { if (matcher.find()) { String variableName = matcher.group(1); Object variableValue; if (variableName.equals("$")) { variableValue = "$"; } else { variableValue = variableHelper.resolve(variableName); } logger.debug("Found variable " + variableName + " = " + variableValue); text.append(textWithVars.substring(currentIndex, matcher.start())); text.append(variableValue); currentIndex = matcher.end(); } } text.append(textWithVars.substring(currentIndex)); return text.toString(); }