Example usage for java.util.regex Matcher replaceFirst

List of usage examples for java.util.regex Matcher replaceFirst

Introduction

In this page you can find the example usage for java.util.regex Matcher replaceFirst.

Prototype

public String replaceFirst(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces the first subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:org.openmrs.module.formentry.PublishInfoPath.java

public static void removeConceptNamesInXslHelper(BufferedReader xslReader, PrintWriter tmpXslWriter)
        throws IOException {
    String line = xslReader.readLine();
    while (line != null) {
        Matcher m = hl7ConceptNamePatternWithOldPreciseName.matcher(line);
        if (m.find()) {
            /*/*from w w  w. j  av a  2  s.co m*/
             * String conceptId = m.group(2); Concept concept =
             * cs.getConcept(new Integer(conceptId)); if (concept == null) {
             * throw new IOException("xsl \"" + xslFilename +
             * "\" contains unknown concept: " + m.group(3) + "(" +
             * conceptId + ")"); } else { ConceptName matchingConceptName =
             * findNameMatching(m.group(3), concept); String appendedHl7 =
             * ""; if (matchingConceptName != null) { appendedHl7 =
             * m.group(1) + FormUtil.conceptToString(concept,
             * matchingConceptName) + m.group(m.groupCount()); } else {
             * appendedHl7 = m.group(1) + FormUtil.conceptToString(concept,
             * defaultLocale) + m.group(m.groupCount()); }
             * 
             * line = m.replaceFirst(appendedHl7); }
             */
            String withoutPreciseName = m.group(1) + m.group(7);
            log.debug("---------------");
            for (int i = 0; i < 6; ++i)
                log.error(i + " -> " + m.group(i));
            line = m.replaceFirst(withoutPreciseName);
        } else {
            tmpXslWriter.println(line);
            line = xslReader.readLine();
        }
    }
}

From source file:org.jahia.modules.macros.filter.MacrosFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (StringUtils.isEmpty(previousOut)) {
        return previousOut;
    }//from w ww. jav  a2  s .  co  m
    long timer = System.currentTimeMillis();
    boolean evaluated = false;

    Matcher matcher = macrosPattern.matcher(previousOut);
    while (matcher.find()) {
        evaluated = true;
        String macroName = matcher.group(1);
        String[] macro = getMacro(macroName);
        if (macro != null) {
            try {
                // execute macro
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]);
                ScriptContext scriptContext = scriptEngine.getContext();
                scriptContext.setWriter(new StringWriter());
                scriptContext.setErrorWriter(new StringWriter());
                scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher));
                String scriptResult = scriptContext.getWriter().toString().trim();
                previousOut = matcher.replaceFirst(scriptResult);
            } catch (ScriptException e) {
                logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(),
                        e);
                previousOut = matcher.replaceFirst(macroName);
            }
            matcher = macrosPattern.matcher(previousOut);
        } else if (replaceByErrorMessageOnMissingMacros) {
            previousOut = matcher.replaceFirst("macro " + macroName + " not found");
            logger.warn("Unknown macro '{}'", macroName);
            matcher = macrosPattern.matcher(previousOut);
        }
    }

    if (evaluated && logger.isDebugEnabled()) {
        logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer));
    }
    return previousOut;
}

From source file:de.geeksfactory.opacclient.apis.Pica.java

@Override
public List<SearchField> getSearchFields() throws IOException, JSONException {
    if (!initialised) {
        start();//from w w w.  j av a 2s.  c  om
    }

    String html = httpGet(opac_url + "/LNG=" + getLang() + "/DB=" + db + "/ADVANCED_SEARCHFILTER",
            getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    List<SearchField> fields = new ArrayList<>();

    Elements options = doc.select("select[name=IKT0] option");
    for (Element option : options) {
        TextSearchField field = new TextSearchField();
        field.setDisplayName(option.text());
        field.setId(option.attr("value"));
        field.setHint("");
        field.setData(new JSONObject("{\"ADI\": false}"));

        Pattern pattern = Pattern.compile("\\[X?[A-Za-z]{2,3}:?\\]|\\(X?[A-Za-z]{2,3}:?\\)");
        Matcher matcher = pattern.matcher(field.getDisplayName());
        if (matcher.find()) {
            field.getData().put("meaning", matcher.group().replace(":", "").toUpperCase());
            field.setDisplayName(matcher.replaceFirst("").trim());
        }

        fields.add(field);
    }

    Elements sort = doc.select("select[name=SRT]");
    if (sort.size() > 0) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName(sort.first().parent().parent().select(".longval").first().text());
        field.setId("SRT");
        for (Element option : sort.select("option")) {
            field.addDropdownValue(option.attr("value"), option.text());
        }
        fields.add(field);
    }

    for (Element input : doc.select("input[type=text][name^=ADI]")) {
        TextSearchField field = new TextSearchField();
        field.setDisplayName(input.parent().parent().select(".longkey").text());
        field.setId(input.attr("name"));
        field.setHint(input.parent().select("span").text());
        field.setData(new JSONObject("{\"ADI\": true}"));
        fields.add(field);
    }

    for (Element dropdown : doc.select("select[name^=ADI]")) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName(dropdown.parent().parent().select(".longkey").text());
        field.setId(dropdown.attr("name"));
        for (Element option : dropdown.select("option")) {
            field.addDropdownValue(option.attr("value"), option.text());
        }
        fields.add(field);
    }

    Elements fuzzy = doc.select("input[name=FUZZY]");
    if (fuzzy.size() > 0) {
        CheckboxSearchField field = new CheckboxSearchField();
        field.setDisplayName(fuzzy.first().parent().parent().select(".longkey").first().text());
        field.setId("FUZZY");
        fields.add(field);
    }

    Elements mediatypes = doc.select("input[name=ADI_MAT]");
    if (mediatypes.size() > 0) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName("Materialart");
        field.setId("ADI_MAT");

        field.addDropdownValue("", "Alle");
        for (Element mt : mediatypes) {
            field.addDropdownValue(mt.attr("value"),
                    mt.parent().nextElementSibling().text().replace("\u00a0", ""));
        }
        fields.add(field);
    }

    return fields;
}

From source file:de.escidoc.core.test.sb.SearchTestBase.java

/**
 * check if public-status, version-number and latest-version-numer are as expected.
 * //w ww . j a  v a2s .  c  o m
 * @param xml
 *            String searchResult
 * @param versionCheckMap
 *            HashMap with objectIds + expected version info.
 * @throws Exception
 *             e
 */
protected void checkVersions(final String xml, final Map<String, HashMap<String, String>> versionCheckMap)
        throws Exception {
    Document doc = getDocument(xml);
    Pattern objIdPattern = Pattern.compile("\\$\\{objId\\}");
    Matcher objIdMatcher = objIdPattern.matcher("");
    Pattern objTypePattern = Pattern.compile("\\$\\{objType\\}");
    Matcher objTypeMatcher = objTypePattern.matcher("");
    String publicStatusXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/public-status";
    String versionNumberXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/version/number";
    String latestVersionNumberXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/latest-version/number";

    for (String key : versionCheckMap.keySet()) {
        objIdMatcher.reset(publicStatusXpath);
        String replacedPublicStatusXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedPublicStatusXpath);
        replacedPublicStatusXpath = objTypeMatcher.replaceFirst(versionCheckMap.get(key).get("objectType"));

        objIdMatcher.reset(versionNumberXpath);
        String replacedVersionNumberXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedVersionNumberXpath);
        replacedVersionNumberXpath = objTypeMatcher.replaceFirst(versionCheckMap.get(key).get("objectType"));

        objIdMatcher.reset(latestVersionNumberXpath);
        String replacedLatestVersionNumberXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedLatestVersionNumberXpath);
        replacedLatestVersionNumberXpath = objTypeMatcher
                .replaceFirst(versionCheckMap.get(key).get("objectType"));

        Node publicStatus = selectSingleNode(doc, replacedPublicStatusXpath);
        Node versionNumber = selectSingleNode(doc, replacedVersionNumberXpath);
        Node latestVersionNumber = selectSingleNode(doc, replacedLatestVersionNumberXpath);
        assertEquals("Public-Status not as expected", versionCheckMap.get(key).get("expectedPublicStatus"),
                publicStatus.getTextContent());
        assertEquals("Version-Number not as expected", versionCheckMap.get(key).get("expectedVersionNumber"),
                versionNumber.getTextContent());
        assertEquals("Latest-Version-Number not as expected",
                versionCheckMap.get(key).get("expectedLatestVersionNumber"),
                latestVersionNumber.getTextContent());
    }
}

From source file:org.openanzo.client.cli.QueryCommand.java

private void prettyPrintGlitterParseError(CommandContext context, String fullQuery, AnzoException e,
        int hiddenPrefixCount) {
    if (e.getErrorCode() != ExceptionConstants.GLITTER.PARSE_EXCEPTION) {
        throw new AnzoRuntimeException(ExceptionConstants.GLITTER.PRINTING_EXCEPTION_FAILED);
    }//from  w w  w  .j ava2s  . c o m

    if (e.getArgs().length < 1) {
        return;
    }
    String error = (e.getArgs().length == 2) ? e.getArgs()[1] : e.toString();
    Matcher matcher = Pattern.compile(GLITTER_LINE_COLUMN_PATTERN).matcher(error);

    // if no line and column numbers are in the parse error, just print it
    if (!matcher.find()) {
        context.writeError(error);
        return;
    }

    // got a line and column number
    // use them to print a more detailed error message, showing the actual line where the error occurred and putting a caret under the
    // column where the error occurred.
    int line = Integer.parseInt(matcher.group(1));
    int column = Integer.parseInt(matcher.group(2));

    // adjust the line number to match the input query.  If prefixes were implicitly added, reduce the line number to account for them.
    context.writeError("Parse error: "
            + matcher.replaceFirst("at line " + (line - hiddenPrefixCount) + ", column " + column + "."));

    // print the line that caused the error.
    String[] lines = fullQuery.split(NEWLINE_PATTERN);
    if (lines.length >= line) {
        context.writeError(lines[line - 1]);
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < column; i++) {
        sb.append(" ");
    }
    sb.append("^");
    context.writeError(sb.toString());
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Copy PATH to MEDIADIR and return new filename. If the same name exists, compare checksums.
 * /* w w w.  j  av  a 2 s  .  c  o  m*/
 * @param opath The path where the media file exists before adding it.
 * @return The filename of the resulting file.
 */
public String addFile(String opath) {
    String mdir = getDir();
    // remove any dangerous characters
    String base = fDangerousCharacters.matcher(new File(opath).getName()).replaceAll("");
    // if it doesn't exist, copy it directly
    File newMediaFile = new File(mdir, base);
    String dst = newMediaFile.getAbsolutePath();
    if (!newMediaFile.exists()) {
        try {
            Utils.copyFile(new File(opath), newMediaFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base;
    }
    if (filesIdentical(opath, dst)) {
        return base;
    }
    // otherwise, find a unique name
    String root, ext;
    int extIndex = base.lastIndexOf('.');
    if (extIndex == 0 || extIndex == -1) {
        root = base;
        ext = "";
    } else {
        root = base.substring(0, extIndex);
        ext = base.substring(extIndex);
    }
    StringBuilder sb = null;
    String path = null;
    Matcher m = null;
    int n = 0;
    while (true) {
        sb = new StringBuilder(mdir);
        path = sb.append(File.separatorChar).append(root).append(ext).toString();
        newMediaFile = new File(path);
        if (!newMediaFile.exists()) {
            break;
        }
        m = fFileOrdinal.matcher(root);
        if (!m.find()) {
            root = root.concat(" (1)");
        } else {
            n = Integer.parseInt(m.group(1));
            root = m.replaceFirst(" (" + String.valueOf(n + 1) + ")");
        }
    }
    // copy and return
    try {
        Utils.copyFile(new File(opath), newMediaFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return newMediaFile.getName();
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaIngestController.java

private String doRename(String oldNamespace, String newNamespace) {
    String uri = null;/*from  ww w .  ja  v a2 s  . c  o  m*/
    String result = null;
    Integer counter = 0;
    Boolean namespacePresent = false;
    RDFService rdfService = ModelAccess.on(getServletContext()).getRDFService();
    try {
        Model baseOntModel = RDFServiceGraph
                .createRDFServiceModel(new RDFServiceGraph(rdfService, ABOX_ASSERTIONS));
        OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel();
        List<String> urisToChange = new LinkedList<String>();
        ontModel.enterCriticalSection(Lock.READ);
        try {
            Iterator<Individual> indIter = ontModel.listIndividuals();
            while (indIter.hasNext()) {
                Individual ind = indIter.next();
                String namespace = ind.getNameSpace();
                if (namespace != null) {
                    if (oldNamespace.equals(namespace)) {
                        uri = ind.getURI();
                        urisToChange.add(uri);
                        namespacePresent = true;
                    }
                }
            }
        } finally {
            ontModel.leaveCriticalSection();
        }
        if (!namespacePresent) {
            result = "no resources renamed";
            return result;
        }
        for (String oldURIStr : urisToChange) {
            long time1 = System.currentTimeMillis();
            Resource res = baseOntModel.getResource(oldURIStr);
            long time2 = System.currentTimeMillis();
            String newURIStr = null;
            Pattern p = Pattern.compile(oldNamespace);
            String candidateString = res.getURI();
            Matcher matcher = p.matcher(candidateString);
            newURIStr = matcher.replaceFirst(newNamespace);
            long time3 = System.currentTimeMillis();
            log.debug("time to get new uri: " + Long.toString(time3 - time2));
            log.debug("Renaming " + oldURIStr + " to " + newURIStr);

            String whereClause = "} WHERE { \n" + "  GRAPH <" + ABOX_ASSERTIONS + "> { \n" + "   { <"
                    + oldURIStr + "> ?p <" + oldURIStr + "> } \n " + "     UNION \n" + "   { <" + oldURIStr
                    + "> ?q ?o } \n " + "     UNION \n" + "   { ?s ?r <" + oldURIStr + "> } \n" + "  } \n"
                    + "}";

            String removeQuery = "CONSTRUCT { \n" + "   <" + oldURIStr + "> ?p <" + oldURIStr + "> . \n "
                    + "   <" + oldURIStr + "> ?q ?o . \n " + "   ?s ?r <" + oldURIStr + "> \n" + whereClause;

            String addQuery = "CONSTRUCT { \n" + "   <" + newURIStr + "> ?p <" + newURIStr + "> . \n " + "   <"
                    + newURIStr + "> ?q ?o . \n " + "   ?s ?r <" + newURIStr + "> \n" + whereClause;
            try {
                ChangeSet cs = rdfService.manufactureChangeSet();
                cs.addAddition(
                        rdfService.sparqlConstructQuery(addQuery, RDFService.ModelSerializationFormat.N3),
                        RDFService.ModelSerializationFormat.N3, ABOX_ASSERTIONS);
                cs.addRemoval(
                        rdfService.sparqlConstructQuery(removeQuery, RDFService.ModelSerializationFormat.N3),
                        RDFService.ModelSerializationFormat.N3, ABOX_ASSERTIONS);
                rdfService.changeSetUpdate(cs);
            } catch (RDFServiceException e) {
                throw new RuntimeException(e);
            }

            long time4 = System.currentTimeMillis();
            log.debug(" time to rename : " + Long.toString(time4 - time3));
            log.debug(" time for one resource: " + Long.toString(time4 - time1));
            counter++;
        }
        result = counter.toString() + " resources renamed";
        return result;
    } finally {
        if (rdfService != null) {
            rdfService.close();
        }
    }
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

private void processTypeLaunch(final String intentAction, final String intentUri, final String intentType,
        final String intentExtras, final String cfmMsg, String failMsgTemp, final int notifyId) {

    //if you wish, use a default generic fail message whenever undefined. recommended to use this when testing
    if (failMsgTemp.equalsIgnoreCase(""))
        failMsgTemp = "Opening URL failed!";
    final String failMsg = failMsgTemp;

    Pattern pattern = Pattern.compile("\\[ASK:(.*?)\\]");
    final Matcher matcher = pattern.matcher(intentUri);
    int count = 0;
    String askMsg = "";
    while (matcher.find()) {
        count++;//from w  w  w  . ja  v a  2  s.c  o m
        askMsg = matcher.group(1);
    }
    if (count == 1) {
        //confirm alert with text input
        if (BleepActivity.isBackground)
            localNotification("", cfmMsg, notifyId);
        final EditText input = new EditText(BleepActivity.currentBleepActivity);
        DialogInterface.OnClickListener posFunc = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String userInput = input.getText().toString();
                String intentUri2 = matcher.replaceFirst(userInput);
                Intent launchIntent = createIntent(intentAction, intentUri2, intentType, intentExtras);
                startIntent(launchIntent, failMsg, true, cfmMsg, notifyId);
            }
        };
        DialogInterface.OnClickListener negFunc = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // Do nothing.
            }
        };
        showAlertDialog(cfmMsg, askMsg, "OK", posFunc, "Cancel", negFunc, input);
    } else if (!cfmMsg.equalsIgnoreCase("")) {
        //confirm alert, message only, no text input
        final Intent launchIntent = createIntent(intentAction, intentUri, intentType, intentExtras);
        if (!BleepActivity.isTesting && !testIntent(launchIntent)) {
            return;
        }
        if (BleepActivity.isBackground) {
            localNotification("", cfmMsg, launchIntent, failMsg, notifyId);
        } else {
            DialogInterface.OnClickListener posFunc = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    startIntent(launchIntent, failMsg, true, cfmMsg, notifyId);
                }
            };
            DialogInterface.OnClickListener negFunc = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                }
            };
            showAlertDialog("", cfmMsg, "OK", posFunc, "Cancel", negFunc, null);
        }
    } else {
        //no confirm alert
        Intent launchIntent = createIntent(intentAction, intentUri, intentType, intentExtras);
        if (!BleepActivity.isTesting && !testIntent(launchIntent)) {
            return;
        }
        String tmpCfmMsg = "You have been sent a URL to view. Open?";
        if (BleepActivity.isBackground) {
            localNotification("", tmpCfmMsg, launchIntent, failMsg, notifyId);
        } else {
            startIntent(launchIntent, failMsg, true, tmpCfmMsg, notifyId);
        }
    }
}

From source file:com.limewoodmedia.nsdroid.activities.WorldAssembly.java

/**
 * Loads data from the NS API into the overview panels
 *//*from  ww w .  j a  v  a2 s.  c o m*/
private void loadData() {
    errorMessage = getResources().getString(R.string.general_error);
    new AsyncTask<Void, Void, Boolean>() {
        protected void onPreExecute() {
            generalAssembly.onBeforeLoading();
            securityCouncil.onBeforeLoading();
            happenings.setText(R.string.loading);
            gaPage.findViewById(R.id.layout).setVisibility(View.GONE);
            LoadingHelper.startLoading((LoadingView) gaPage.findViewById(R.id.loading));
            scPage.findViewById(R.id.layout).setVisibility(View.GONE);
            LoadingHelper.startLoading((LoadingView) scPage.findViewById(R.id.loading));
        }

        protected Boolean doInBackground(Void... params) {
            try {
                gaData = API.getInstance(WorldAssembly.this).getWAInfo(WACouncil.GENERAL_ASSEMBLY,
                        WAData.Shards.RESOLUTION, WAData.Shards.HAPPENINGS, WAData.Shards.VOTETRACK,
                        WAData.Shards.LAST_RESOLUTION);

                scData = API.getInstance(WorldAssembly.this).getWAInfo(WACouncil.SECURITY_COUNCIL,
                        WAData.Shards.RESOLUTION, WAData.Shards.VOTETRACK, WAData.Shards.LAST_RESOLUTION);

                nationData = API.getInstance(WorldAssembly.this).getNationInfo(
                        NationInfo.getInstance(WorldAssembly.this).getId(), NationData.Shards.NAME,
                        NationData.Shards.GA_VOTE, NationData.Shards.SC_VOTE);

                // Happenings - fetch nation and region names
                Pattern nPattern = Pattern.compile("(.*?)@@([a-z\\d_]+)@@(.*?)");
                Pattern rPattern = Pattern.compile("(.*?)%%([a-z\\d_]+)%%(.*?)");
                Matcher matcher;
                String n, r;
                List<Happening> list = new ArrayList<Happening>(gaData.happenings);
                list.addAll(gaData.happenings);
                for (Happening event : list) {
                    matcher = nPattern.matcher(event.text);
                    while (matcher.matches()) {
                        n = event.text.substring(matcher.start(2), matcher.end(2));
                        n = TagParser.idToName(n);

                        event.text = matcher.replaceFirst(
                                "$1<a href=\"com.limewoodMedia.nsdroid.nation://$2\">" + n + "</a>$3");
                        matcher = nPattern.matcher(event.text);
                    }
                    matcher = rPattern.matcher(event.text);
                    while (matcher.matches()) {
                        r = event.text.substring(matcher.start(2), matcher.end(2));
                        r = TagParser.idToName(r);

                        event.text = matcher.replaceFirst(
                                "$1<a href=\"com.limewoodMedia.nsdroid.region://$2\">" + r + "</a>$3");
                        matcher = rPattern.matcher(event.text);
                    }
                }

                return true;
            } catch (RateLimitReachedException e) {
                e.printStackTrace();
                errorMessage = getResources().getString(R.string.rate_limit_reached);
            } catch (RuntimeException e) {
                e.printStackTrace();
                errorMessage = e.getMessage();
            } catch (UnknownNationException e) {
                e.printStackTrace();
                errorMessage = getResources().getString(R.string.unknown_nation);
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                errorMessage = getResources().getString(R.string.xml_parser_exception);
            } catch (IOException e) {
                e.printStackTrace();
                errorMessage = getResources().getString(R.string.api_io_exception);
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            generalAssembly.onAfterLoading();
            securityCouncil.onAfterLoading();
            gaPage.findViewById(R.id.layout).setVisibility(View.VISIBLE);
            LoadingHelper.stopLoading((LoadingView) gaPage.findViewById(R.id.loading));
            scPage.findViewById(R.id.layout).setVisibility(View.VISIBLE);
            LoadingHelper.stopLoading((LoadingView) scPage.findViewById(R.id.loading));
            if (result) {
                doSetup();
            } else {
                Toast.makeText(WorldAssembly.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        }
    }.execute();
}

From source file:me.Wundero.Ray.utils.TextUtils.java

/**
 * Find all variables in a string and parse it into a text template.
 *///from   ww  w.j a  v a  2 s .c o  m
public static TextTemplate parse(final String i, boolean allowColors) {
    if (i == null) {
        return null;
    }
    String in = i;
    if (!allowColors) {
        in = strip(in);
    }
    in = in.replace("%n", "\n");
    if (!Utils.VAR_PATTERN.matcher(in).find()) {
        return TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(in));
    }
    String[] textParts = in.split(Utils.VAR_PATTERN.pattern());
    if (textParts.length == 0) {
        return TextTemplate.of(TextTemplate.arg(in));
    }
    Matcher matcher = Utils.VAR_PATTERN.matcher(in);
    TextTemplate out = TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(textParts[0]));
    int x = 1;
    while (matcher.reset(in).find()) {
        String mg = matcher.group().substring(1);
        mg = mg.substring(0, mg.length() - 1);
        out = out.concat(TextTemplate.of(TextTemplate.arg(mg)));
        if (x < textParts.length) {
            out = out.concat(TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(textParts[x])));
        }
        in = matcher.replaceFirst("");
        x++;
    }
    return out;
}