public static String getGoalText( final ChallengeGoalData goal, final ChallengeData data, final ChallengeDataModel model) { String rawText = goal.getFormattedString(); if (rawText == null || rawText.length() == 0) { return null; } rawText = (String) ChallengeFormatter.extractValue( rawText, ChallengeFormatter.Type.STRING, model.getParams()); for (Matcher match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText); match.find(); match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText)) { final String name = WakfuTranslator.getInstance() .getString(7, PrimitiveConverter.getInteger(match.group(1)), new Object[0]); rawText = match.replaceFirst(name); } for (Matcher match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText); match.find(); match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText)) { final String name = WakfuTranslator.getInstance() .getString(12, PrimitiveConverter.getInteger(match.group(1)), new Object[0]); rawText = match.replaceFirst(name); } for (Matcher match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText); match.find(); match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText)) { final Long value = data.getVarValue(match.group().substring(1, match.group().length() - 1)); rawText = match.replaceFirst(value.toString()); } return rawText; }
/** * Creates a new {@code UriPathTemplate} from the given {@code uriPattern}. * * @param uriPattern The pattern to be used by the template */ public UriPathTemplate(String uriPattern) { String s = "^" + uriPattern; Matcher m = NAME_SPLAT_PATTERN.matcher(s); while (m.find()) { for (int i = 1; i <= m.groupCount(); i++) { String name = m.group(i); pathVariables.add(name); s = m.replaceFirst(NAME_SPLAT_REPLACEMENT.replaceAll("%NAME%", name)); m.reset(s); } } m = NAME_PATTERN.matcher(s); while (m.find()) { for (int i = 1; i <= m.groupCount(); i++) { String name = m.group(i); pathVariables.add(name); s = m.replaceFirst(NAME_REPLACEMENT.replaceAll("%NAME%", name)); m.reset(s); } } m = FULL_SPLAT_PATTERN.matcher(s); while (m.find()) { s = m.replaceAll(FULL_SPLAT_REPLACEMENT); m.reset(s); } this.uriPattern = Pattern.compile(s + "$"); }
/** * 以给定日期为基准展开宏 * * @param str 含有待展开宏的字符串 * @param dateYmd 基准日期,对应{yyyymmdd},{yyyymmdd-n},{yyyymmdd+n} * @return 展开后的字符串 */ public static String expandMacroDateYmd(String str, Date dateYmd) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Pattern dateYmdPat = Pattern.compile("\\{\\s*yyyymmdd\\s*(([+-])\\s*(\\d+))?\\s*\\}"); String res = str; Matcher matcher = dateYmdPat.matcher(res); while (matcher.find()) { String expr = matcher.group(1); String op = matcher.group(2); String ndays = matcher.group(3); if (StringUtils.isEmpty(expr)) { // 无日期计算部分,直接展开 res = matcher.replaceFirst(sdf.format(dateYmd)); matcher = dateYmdPat.matcher(res); } else if ("+".equals(op)) { // 基准日期+n 天 int n = Integer.parseInt(ndays); res = matcher.replaceFirst(sdf.format(DateUtils.addDays(dateYmd, n))); matcher = dateYmdPat.matcher(res); } else if ("-".equals(op)) { // 基准日期-n 天 int n = -Integer.parseInt(ndays); res = matcher.replaceFirst(sdf.format(DateUtils.addDays(dateYmd, n))); matcher = dateYmdPat.matcher(res); } } return res; }
/** * Creates a count projected query from the given original query. * * @param originalQuery must not be {@literal null}. * @param countProjection may be {@literal null}. * @return * @since 1.6 */ public static String createCountQueryFor(String originalQuery, String countProjection) { Assert.hasText(originalQuery, "OriginalQuery must not be null or empty!"); Matcher matcher = COUNT_MATCH.matcher(originalQuery); String countQuery = null; if (countProjection == null) { String variable = matcher.matches() ? matcher.group(VARIABLE_NAME_GROUP_INDEX) : null; boolean useVariable = variable != null && StringUtils.hasText(variable) && !variable.startsWith("new") && !variable.startsWith("count(") && !variable.contains(","); String replacement = useVariable ? SIMPLE_COUNT_VALUE : COMPLEX_COUNT_VALUE; countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, replacement)); } else { countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, countProjection)); } return countQuery.replaceFirst(ORDER_BY_PART, ""); }
protected void runOnce() { String line = io.readLine(); line = line.replace(" ", ""); // Strip spaces // Keep replacing the leftmost highest precedence subexpression while (true) { Matcher m; // Brackets m = BRACKET.matcher(line); if (m.find()) { line = m.replaceFirst("$1"); continue; } // "Exponentiation" m = EXPONENT.matcher(line); if (m.find()) { int x = Integer.parseInt(m.group(1)); int y = Integer.parseInt(m.group(2)); int z = Integer.parseInt(Math.abs(x) + "" + Math.abs(y)); line = m.replaceFirst(Integer.toString(z)); continue; } // Multiplication, division m = MULT_DIV.matcher(line); if (m.find()) { int x = Integer.parseInt(m.group(1)); int y = Integer.parseInt(m.group(3)); int z = m.group(2).equals("*") ? x * y : x / y; line = m.replaceFirst(Integer.toString(z)); continue; } // Addition, subtraction m = ADD_SUB.matcher(line); if (m.find()) { int x = Integer.parseInt(m.group(1)); int y = Integer.parseInt(m.group(3)); int z = m.group(2).equals("+") ? x + y : x - y; line = m.replaceFirst(Integer.toString(z)); continue; } break; } io.println(line); }
/** * 当前Session中用户所属的组织的名称 组织名称,当前登录用户所属的组织名称,是否带路径 @GROUPNAME(true|false); * * @param cf * @return */ public String eval_GROUPNAME(String cf) { String regex = "@GROUPNAME\\(((false)|(true))\\)"; // 匹配@GROUPNAME公式 Pattern p = Pattern.compile(regex); Matcher mt = p.matcher(cf); P2GManager p2gManager = (P2GManager) SpringContextUtil.getBean("p2gManager"); while (mt.find()) { String gp = mt.group(); String fm = gp.substring(gp.indexOf("(") + 1, gp.indexOf(")")); Boolean flag = Boolean.parseBoolean(fm); String personId = (String) this.sessionAttrs.get(Constants.SESSION_CURRENT_PERSONID); ArrayList<Group> entities = (ArrayList<Group>) p2gManager.findGroupsOfThePerson(personId); // 获得第一个组织名 Group entity = entities.get(0); String groupName = null; if (!flag) { groupName = entity.getGroupName(); // 返回第一个组织名 } else { // 需要获得完整路径 // 当前组织ID groupName = entity.getPathWithText(); } cf = mt.replaceFirst("\"" + groupName + "\""); mt = p.matcher(cf); } return cf; }
/** * CONTEXT公式 * * @param cf * @return */ public String eval_CONTEXT(String cf) { String regex = "(@CONTEXT\\([a-zA-Z0-9\"-\\/_ 年月日:,]+\\))"; // 匹配@VALUE公式 Pattern p = Pattern.compile(regex); Matcher mt = p.matcher(cf); while (mt.find()) { String group = mt.group(); String tmpArray[] = group.split("\""); String varName = tmpArray[1].toUpperCase(); Object value = this.context.getVar(varName); if (value == null) { value = ""; } else { if (value instanceof Date) { String fm = "yyyy-MM-dd"; if (tmpArray.length > 3) { fm = tmpArray[3]; } value = DateUtils.formatDate((Date) value, fm); } } cf = mt.replaceFirst("\"" + value + "\""); mt = p.matcher(cf); } return cf; }
/** * 计算@PARSENUMBER("333.33");公式 * * @param cf * @return */ public String eval_PARSENUMBER(String cf) { String regex = "(@PARSENUMBER\\([0-9|.|\"]*\\))"; // 匹配@VALUE公式 Pattern p = Pattern.compile(regex); Matcher mt = p.matcher(cf); while (mt.find()) { String group = mt.group(); String number = group.substring(group.indexOf("\"") + 1, group.lastIndexOf("\"")); if (NumberUtils.isNumeric(number)) { cf = mt.replaceFirst(number); } else { cf = mt.replaceFirst("0"); } mt = p.matcher(cf); } return cf; }
/** * Get a target subdirectory under current/ for a given block file that is being restored from * trash. * * <p>The subdirectory structure under trash/ mirrors that under current/ to keep implicit memory * of where the files are to be restored. * * @return the target directory to restore a previously deleted block file. */ @VisibleForTesting String getRestoreDirectory(File blockFile) { Matcher matcher = BLOCK_POOL_TRASH_PATH_PATTERN.matcher(blockFile.getParent()); String restoreDirectory = matcher.replaceFirst("$1$2" + STORAGE_DIR_CURRENT + "$4"); LOG.info("Restoring " + blockFile + " to " + restoreDirectory); return restoreDirectory; }
public Token nextToken() throws InvalidCodeException { str = str.trim(); if (pushBack) { pushBack = false; return lastToken; } if (str.equals("")) { return lastToken = new Token(Token.TokenType.EMPTY); } for (TokenData data : tokenDatas) { Matcher matcher = data.getPattern().matcher(str); if (matcher.find()) { String token = matcher.group().trim(); str = matcher.replaceFirst(""); if (data.getTokenType() == Token.TokenType.STRING_LITERAL) { return lastToken = new Token(Token.TokenType.STRING_LITERAL, token.substring(1, token.length() - 1)); } else { return lastToken = new Token(data.getTokenType(), token); } } } throw new InvalidCodeException("Unknown token: " + str.substring(0, str.indexOf(" "))); }
@Override public String solverRandom(int type, String value) { Matcher matcher = PATTERN.matcher(value); matcher.find(); return matcher.replaceFirst( RandomRegistry.getRandomFromSet(Arrays.asList(matcher.group(1).split(", ?")))); }
public static String getGroupPrefixString(String username) { Matcher match = groupRegex.matcher(CoreConfig.groupPrefixFormat); ArrayList<TreeSet<Group>> list = getGroupsList(match, username); String end = ""; StringBuilder temp = new StringBuilder(); for (TreeSet<Group> set : list) { for (Group g : set) { if (g.prefix.trim().isEmpty()) { continue; } if (temp.length() == 0) { temp.append(g.prefix); } else { temp.insert(0, g.prefix + "&r"); } } end = match.replaceFirst(temp.toString()); temp = new StringBuilder(); } return end; }
/** * 条件判断 @IF(表单变量?"":""); aaa && bbb || ccc * * @param cf * @return */ public String eval_IF(String cf) { // "123"+@IF((A>100 && B<100)?@UUID():@VALUE()); String regex = "@IF\\(.*\\)"; // 匹配@IF公式 Pattern p = Pattern.compile(regex); Matcher mt = p.matcher(cf); while (mt.find()) { String group = mt.group(); String condition = group.substring(group.indexOf("(") + 1, group.indexOf("?")); String v1 = group.substring(group.indexOf("?") + 1, group.indexOf(":")); String v2 = group.substring(group.indexOf(":") + 1, group.lastIndexOf(")")); Interpreter i = new Interpreter(); String v = "\"\""; try { initEvalContext(i); Boolean ret = (Boolean) i.eval(condition); if (ret == true) { v = v1; } else { v = v2; } mt = p.matcher(cf); } catch (Exception ex) { // ex.printStackTrace(); } cf = mt.replaceFirst(v); } return cf; }
/** * Normalize components of the given file path, removing any environment- or test-run dependent * components. For example, substitutes the unique id portion of Impala generated file names with * a fixed literal. Subclasses should override to do filesystem specific cleansing. */ protected Path cleanseFilePath(Path path) { String fileName = path.getName(); Pattern pattern = Pattern.compile("\\w{16}-\\w{16}_\\d+_data"); Matcher matcher = pattern.matcher(fileName); fileName = matcher.replaceFirst("<UID>_data"); return new Path(path.getParent(), fileName); }
/** Capitalize a.m./p.m and remove the all '.' characters. */ private String formatAmPm(String dateTime) { final Pattern AM_PM = Pattern.compile("(a.m.|p.m.)"); Matcher matcher = AM_PM.matcher(dateTime); matcher.find(); String capitalized = matcher.group(1).toUpperCase(); return matcher.replaceFirst(capitalized).replaceAll("\\.", ""); }
public Lexer2(String str) { tokenInfos = new LinkedList<>(); tokens = new LinkedList<>(); add("PARTDESC|PARTNO|PNC|INVOICEDESC|SUNDRYCODE", 10); add("\\(", 6); add("\\)", 7); add("\\=|LIKE", 11); add("OR", 1); add("AND", 2); add("[0-9]+", 12); add("'[%][0-9]+[%]'", 12); add("\\'(.*?)\\'", 12); String s = str.trim(); tokens.clear(); while (!s.equals("")) { boolean match = false; for (TokenInfo info : tokenInfos) { Matcher m = info.regex.matcher(s); if (m.find()) { match = true; String tok = m.group().trim(); s = m.replaceFirst("").trim(); tokens.add(new Token(info.token, tok)); break; } } if (!match) { System.out.println("Unexpected character in input: " + s); } } }
/** Extract a condition from the working string. */ @Override @SuppressWarnings("nls") public TalkConsequence extract() { if (getNewLine() == null) { throw new IllegalStateException("Can't extract if no state set."); } final Matcher stringMatcher = STRING_FIND.matcher(getNewLine()); if (stringMatcher.find()) { final AdvancedNumber level = AdvNumber.getNumber(stringMatcher.group(1)); setLine(stringMatcher.replaceFirst(EMPTY_STRING)); if (level == null) { reportError( String.format( Lang.getMsg(getClass(), "number"), stringMatcher.group(1), stringMatcher.group(0))); return extract(); } final ConsequenceTreasure treasureCons = ConsequenceTreasure.getInstance(); treasureCons.setData(level); return treasureCons; } return null; }
public void doReplacement() { EditWindow currentWindow = editor.getActiveWindow(); if (currentWindow == null || getFindTextField().getText().length() == 0) { // launch error dialog? return; } JEditorPane editorPane = currentWindow.getEditorPane(); String text = editorPane.getSelectedText(); if (text == null) { // no selection return; } Matcher m = getCurrentPattern().matcher(text); if (m.matches()) { String replacement = getReplaceTextField().getText(); if (getRegexButton().isSelected()) { replacement = m.replaceFirst(replacement); } editorPane.replaceSelection(replacement); } }
private static String removeComments(String line) { Matcher m = commentPattern.matcher(line); line = m.replaceFirst(""); Matcher m1 = escapedCommentCharacterPattern.matcher(line); line = m1.replaceAll(commentIntroducingCharacter); return line; }
@Override public String suggestSdkName(String currentSdkName, String sdkHome) { final String suggestedName; if (currentSdkName != null && !currentSdkName.isEmpty()) { final Matcher matcher = VERSION_STRING_PATTERN.matcher(currentSdkName); final boolean replaceNameWithVersion = matcher.matches(); if (replaceNameWithVersion) { // user did not change name -> set it automatically final String versionString = getVersionString(sdkHome); suggestedName = versionString == null ? currentSdkName : matcher.replaceFirst("$1" + versionString + "$3"); } else { suggestedName = currentSdkName; } } else { String versionString = getVersionString(sdkHome); suggestedName = versionString == null ? ProjectBundle.message("sdk.java.unknown.name") : getVersionNumber(versionString); } return suggestedName; }
@Override public DatePickerPanel waitForElementsToLoad() { for (Map.Entry<Month, ExtendedWebElement> entry : this.monthElements.entrySet()) { entry .getValue() .setUnderlyingWebElement( this.driver.findElement( By.className( appProps.getELEMENT_CLASS_PREFIX_MONTH() + (entry.getKey().getValue() - 1)))); } List<WebElement> yearButtons = this.getDriver().findElementsByClassName(appProps.getELEMENT_CLASS_YEAR_BUTTON()); for (WebElement yearButton : yearButtons) { Matcher yearButtonMatcher = YEAR_BUTTON_CLASS_PATTERN.matcher( yearButton.getAttribute(appProps.getATTRIBUTE_NAME_CLASS())); this.yearElements.put( yearButtonMatcher.replaceFirst("$1"), new ExtendedWebElement(this, yearButton)); } this.okButton.setUnderlyingWebElement( this.driver.findElement(By.className(appProps.getELEMENT_ID_OK_BUTTON()))); this.cancelButton.setUnderlyingWebElement( this.driver.findElement(By.className(appProps.getELEMENT_ID_CANCEL_BUTTON()))); return this; }
static void testReplace() { Pattern pattern = Pattern.compile("(d.)"); Matcher m = pattern.matcher("abcdefgd"); System.out.println(m.replaceFirst("12$1\3")); System.out.println("abcdefgd".replaceFirst("(d.)", "12$1\\3")); System.out.println("abcdef\\\\gd "); }
private static String setBase(String content, String base) { // remove base tag if it exists Pattern basePattern = Pattern.compile("<base.*?>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher baseMatcher = basePattern.matcher(content); if (baseMatcher.find()) { // base is already set return content; } // add new base tag Pattern headPattern = Pattern.compile("<head>(.*?)</head>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher headMatcher = headPattern.matcher(content); if (headMatcher.find()) { StringBuffer newHead = new StringBuffer(); newHead.append("<head>\n"); newHead.append("<base href=\""); newHead.append(base); newHead.append("\" target=\"_blank\"/>\n"); newHead.append(headMatcher.group(1)); newHead.append("\n"); newHead.append("</head>\n"); content = headMatcher.replaceFirst(newHead.toString()); } return content; }
public String apply(String word) { Matcher matcher = regex.matcher(word); boolean find = matcher.find(); if (!find) { return null; } return matcher.replaceFirst(replacement); }
/** * Get a target subdirectory under trash/ for a given block file that is being deleted. * * <p>The subdirectory structure under trash/ mirrors that under current/ to keep implicit memory * of where the files are to be restored (if necessary). * * @return the trash directory for a given block file that is being deleted. */ public String getTrashDirectory(File blockFile) { if (isTrashAllowed(blockFile)) { Matcher matcher = BLOCK_POOL_CURRENT_PATH_PATTERN.matcher(blockFile.getParent()); String trashDirectory = matcher.replaceFirst("$1$2" + TRASH_ROOT_DIR + "$4"); return trashDirectory; } return null; }
/** Inverse of {@link #doMigrate}. */ private void unmigrateBuildsDir(File builds) throws Exception { File mapFile = new File(builds, MAP_FILE); if (!mapFile.isFile()) { System.err.println(builds + " does not look to have been migrated yet; skipping"); return; } for (File build : builds.listFiles()) { int number; try { number = Integer.parseInt(build.getName()); } catch (NumberFormatException x) { continue; } File buildXml = new File(build, "build.xml"); if (!buildXml.isFile()) { System.err.println(buildXml + " did not exist"); continue; } String xml = FileUtils.readFileToString(buildXml, Charsets.UTF_8); Matcher m = TIMESTAMP_ELT.matcher(xml); if (!m.find()) { System.err.println(buildXml + " did not contain <timestamp> as expected"); continue; } long timestamp = Long.parseLong(m.group(1)); String nl = m.group(2); xml = m.replaceFirst(" <number>" + number + "</number>" + nl); m = ID_ELT.matcher(xml); String id; if (m.find()) { id = m.group(1); xml = m.replaceFirst(""); } else { // Post-migration build. We give it a new ID based on its timestamp. id = legacyIdFormatter.format(new Date(timestamp)); } FileUtils.write(buildXml, xml, Charsets.UTF_8); if (!build.renameTo(new File(builds, id))) { System.err.println(build + " could not be renamed"); } Util.createSymlink(builds, id, Integer.toString(number), StreamTaskListener.fromStderr()); } Util.deleteFile(mapFile); System.err.println(builds + " has been restored to its original format"); }
private String getWordMatchingPattern() { Matcher m = STRIP_PATTERN.matcher(pattern); if (!m.matches()) { throw new IllegalStateException("internal pattern mismatch:" + pattern); } String content = m.group(GROUP_CONTENT); return pattern.replaceFirst( content, m.replaceFirst("(?<" + GROUP_CONTENT + ">" + content + ")")); }
/** * A helper method to strip unwanted whitespace from an input text. * * <p>This method is expected to be called on a input text consiting of multiple lines. * * @param text * @return not null */ public static final String stripws(String text) { Pattern P; Matcher m; String t; int e, n; // Compile a regex matching all whitespace starting from the begin of // input till the first non-whitespace character. Note, that '\s' // matches EOL as well as classical whitespace. P = makeregex("^[ \\t\\f]*(?:\\n|\\r\\n)(\\s*)"); // Create matcher object, then test whether basic regex matches. If not // then there is no \eol between begin-of-input and first non-ws char - // in which case we do not strip any ws on purpose. m = P.matcher(text); if (m.find() == false) { return text; } // Calculate the number of ws characters between first non-ws character // and \eol before that character. Such a character must exist, other- // wise regex 'P' could not have matched. e = m.end(); n = 0; while (e > 0) { switch (text.charAt(--e)) { case '\n': break; default: n = n + 1; } } // Remove initial ws including \eol. t = m.replaceFirst("$1"); if (n > 0) { // Compile a pattern on the fly that matches a newline followed by // at most n whitespace characters (but newline). P = makeregex("(?m)(^|\\A)[ \\t\\f]{1," + n + "}"); m = P.matcher(t); t = m.replaceAll(""); } // Eventually remove trailing whitespace // Warning: do not use '$' to denote ONLY the end of input - this can // be tricky. Cause '$' also matches the *last* \eol before \eof. Better // to use \z cause always means \eof. See also unit cases for further // details. P = makeregex("\\n[ \\t\\f]*\\z"); m = P.matcher(t); t = m.replaceAll(""); return t; }
/** * Reverts a string from camel case. * * @param s The string to be transformed. * @param space The new word separator character. * @return The new string. */ public static String unCamelCase(String s, char space) { final Pattern pattern = Pattern.compile("([a-z0-9])([A-Z])"); Matcher matcher = pattern.matcher(s); String[] pieces = pattern.split(s); while (matcher.find()) { s = matcher.replaceFirst(matcher.group(1) + space + matcher.group(2).toLowerCase()); matcher.reset(s); } return s; }
public String replaceURL(Pattern pattern, String toReplaceString) { final Matcher matcher = pattern.matcher(toReplaceString); if (matcher.find()) { toReplaceString = matcher.replaceFirst(linkStrings.get(uneed2TranslateElementIndex)); uneed2TranslateElementIndex++; return replaceURL(pattern, toReplaceString); } else { return toReplaceString; } }