List of usage examples for java.util.regex Matcher quoteReplacement
public static String quoteReplacement(String s)
From source file:com.sk89q.craftbook.sponge.mechanics.HeadDrops.java
@Override public String performCustomConversions(String input) { StringBuilder headTable = new StringBuilder(); headTable.append("Mob Head Drops\n"); headTable.append("=================\n\n"); headTable.append("HeadDrops supports all mob heads in the base game, as well as many more.\n\n"); int mobTypeLength = "Mob".length(), headImageLength = "Image".length(); for (Map.Entry<EntityType, GameProfile> entry : mobSkullMap.entrySet()) { if (entry.getKey().getName().length() > mobTypeLength) mobTypeLength = entry.getKey().getName().length(); if ((".. image:: https://minotar.net/helm/" + entry.getValue().getName().orElse("") + "/64.png") .length() > headImageLength) headImageLength = (".. image:: https://minotar.net/helm/" + entry.getValue().getName().orElse("") + "/64.png").length(); }/* ww w . j ava 2 s.co m*/ String border = createStringOfLength(mobTypeLength, '=') + ' ' + createStringOfLength(headImageLength, '='); headTable.append(border).append('\n'); headTable.append(padToLength("Mob", mobTypeLength + 1)).append(padToLength("Image", headImageLength + 1)) .append('\n'); headTable.append(border).append('\n'); for (Map.Entry<EntityType, GameProfile> entry : mobSkullMap.entrySet()) { headTable.append(padToLength(entry.getKey().getName(), mobTypeLength + 1)).append(padToLength( ".. image:: https://minotar.net/helm/" + entry.getValue().getName().orElse("") + "/64.png", headImageLength + 1)).append('\n'); } headTable.append(border).append('\n'); return HEAD_DROPS_TABLE_PATTERN.matcher(input).replaceAll(Matcher.quoteReplacement(headTable.toString())); }
From source file:gtu._work.ui.RegexCatchReplacer_Ebao.java
/** * @param fromPattern/*from w w w . ja v a 2 s . co m*/ * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ void replacer(String fromPattern, String toFormat, String replaceText) { try { Pattern pattern = Pattern.compile(fromPattern); Matcher matcher = pattern.matcher(replaceText); Map<String, Integer> tmap = new LinkedHashMap<String, Integer>(); String tempStr = null; for (; matcher.find();) { tempStr = toFormat.toString(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); if (!tmap.containsKey(tempStr)) { tmap.put(tempStr, 0); } tmap.put(tempStr, tmap.get(tempStr) + 1); } } DefaultTableModel model = JTableUtil.createModel(true, "match", "count"); for (String str : tmap.keySet()) { model.addRow(new Object[] { str, tmap.get(str) }); } setTitle("total : " + model.getRowCount()); resultArea.setModel(model); // ebao? JTableUtil resultAreaUtil = JTableUtil.newInstance(resultArea); DefaultTableModel model2 = JTableUtil.createModel(true, "msgId", "Label"); boolean isExactSearch = exactEbaoSearchChk.isSelected(); ebaoTable.setModel(model2); for (int ii = 0; ii < model.getRowCount(); ii++) { String msgId = (String) resultAreaUtil.getRealValueAt(ii, 0); callEbaoMsgId(msgId, isExactSearch); } } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); ex.printStackTrace(); } }
From source file:com.hexidec.ekit.component.HTMLUtilities.java
private static String addColgroups(String html, List<String> colgroups) { StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile("<table\\b[^>]*>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(html);/* w ww . java 2 s .c om*/ if (!m.find()) { return html; } int i = 0; do { String colgroup = colgroups.get(i++); m.appendReplacement(sb, Matcher.quoteReplacement(m.group() + colgroup)); } while (m.find()); m.appendTail(sb); return sb.toString(); }
From source file:com.mediaworx.intellij.opencmsplugin.sync.SyncJob.java
private void pullModuleManifests() { // collect the module names in a List List<String> moduleNames = new ArrayList<String>(syncList.getOcmsModules().size()); for (OpenCmsModule ocmsModule : syncList.getOcmsModules()) { moduleNames.add(ocmsModule.getModuleName()); }/* ww w . jav a 2 s .com*/ if (moduleNames.size() > 0) { try { // pull the module manifests Map<String, String> manifestInfos = plugin.getPluginConnector().getModuleManifests(moduleNames); for (OpenCmsModule ocmsModule : syncList.getOcmsModules()) { if (manifestInfos.containsKey(ocmsModule.getModuleName())) { // put the manifest to a file String manifestPath = ocmsModule.getManifestRoot() + "/manifest_stub.xml"; String manifest = manifestInfos.get(ocmsModule.getModuleName()); if (ocmsModule.isSetSpecificModuleVersionEnabled() && StringUtils.isNotEmpty(ocmsModule.getModuleVersion())) { manifest = manifest.replaceFirst("<version>[^<]*</version>", "<version>" + Matcher.quoteReplacement(ocmsModule.getModuleVersion()) + " </version>"); } manifest = PluginTools.ensureUnixNewline(manifest) + "\n"; FileUtils.writeStringToFile(new File(manifestPath), manifest, Charset.forName("UTF-8")); console.info("PULL: " + manifestPath + " pulled from OpenCms"); } else { LOG.warn("No manifest found for module " + ocmsModule.getModuleName()); } } } catch (OpenCmsConnectorException e) { console.error(e.getMessage()); } catch (IOException e) { Messages.showDialog( "There was an error pulling the module manifest files from OpenCms.\nIs the connector module installed?", "Error", new String[] { "Ok" }, 0, Messages.getErrorIcon()); LOG.warn("There was an Exception pulling the module manifests", e); } } }
From source file:org.nuxeo.ecm.social.workspace.gadgets.webengine.SocialWebEngineRoot.java
public String escapePath(String text) { // text = text.replaceAll("\"", Matcher.quoteReplacement("\\\\\"")); text = text.replaceAll("'", Matcher.quoteReplacement("\\\'")); try {/*from w ww.ja va 2 s . c o m*/ text = URIUtil.encodePath(text); } catch (Exception e) { log.debug("failed to encode:" + text, e); } return text; }
From source file:org.finra.herd.service.helper.Hive13DdlGenerator.java
/** * Gets a regex to match Hive partition sub-directories. * * @param partitionColumns the list of partition columns * * @return the newly created regex to match Hive partition sub-directories. *//*w w w . j a v a 2 s . c o m*/ public String getHivePathRegex(List<SchemaColumn> partitionColumns) { StringBuilder sb = new StringBuilder(26); sb.append("^(?:"); // Start a non-capturing group for the entire regex. // For each partition column, add a regular expression to match "<COLUMN_NAME|COLUMN-NAME>=<VALUE>" sub-directory. for (SchemaColumn partitionColumn : partitionColumns) { sb.append("(?:"); // Start a non-capturing group for the remainder of the regex. sb.append("(?:"); // Start a non-capturing group for folder markers. sb.append("\\/"); // Add a trailing "/". sb.append('|'); // Ann an OR. sb.append(REGEX_S3_EMPTY_PARTITION); // Add a trailing "_$folder$", which represents an empty partition in S3. sb.append(')'); // Close a non-capturing group for folder markers. sb.append('|'); // Add an OR. sb.append("(?:"); // Start a non-capturing group for "/<column name>=<column value>". sb.append("\\/"); // Add a "/". // We are using a non-capturing group for the partition column names here - this is done by adding "?:" to the beginning of a capture group. sb.append("(?:"); // Start a non-capturing group for column name. sb.append("(?i)"); // Match partition column names case insensitive. sb.append(Matcher.quoteReplacement(partitionColumn.getName())); sb.append('|'); // Add an OR. // For sub-partition folder, we do support partition column names having all underscores replaced with hyphens. sb.append(Matcher.quoteReplacement(partitionColumn.getName().replace("_", "-"))); sb.append(')'); // Close a non-capturing group for column name. sb.append("=([^/]+)"); // Add a capturing group for a column value. } // Add additional regular expression for the trailing empty folder marker and/or "/" followed by an optional file name. sb.append("(?:"); // Start a non-capturing group for folder markers and an optional file name. sb.append("\\/"); // Add a trailing "/". sb.append("[^/]*"); // Add an optional file name. sb.append('|'); // Add an OR. sb.append(REGEX_S3_EMPTY_PARTITION); // Add a trailing "_$folder$", which represents an empty partition in S3. sb.append(")"); // Close a non-capturing group for folder markers and an optional file name. // Close all non-capturing groups that are still open. for (int i = 0; i < 2 * partitionColumns.size(); i++) { sb.append(')'); } sb.append(')'); // Close a non-capturing group for the entire regex. sb.append('$'); return sb.toString(); }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public static String[] subsetStringVector(InputStream in, int column, int numCases) { String[] retVector = new String[numCases]; Scanner scanner = new Scanner(in); scanner.useDelimiter("\\n"); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { if (scanner.hasNext()) { String[] line = (scanner.next()).split("\t", -1); retVector[caseIndex] = line[column]; if ("".equals(line[column])) { // An empty string is a string missing value! // An empty string in quotes is an empty string! retVector[caseIndex] = null; } else { // Strip the outer quotes: line[column] = line[column].replaceFirst("^\\\"", ""); line[column] = line[column].replaceFirst("\\\"$", ""); // We need to restore the special characters that // are stored in tab files escaped - quotes, new lines // and tabs. Before we do that however, we need to // take care of any escaped backslashes stored in // the tab file. I.e., "foo\t" should be transformed // to "foo<TAB>"; but "foo\\t" should be transformed // to "foo\t". This way new lines and tabs that were // already escaped in the original data are not // going to be transformed to unescaped tab and // new line characters! String[] splitTokens = line[column].split(Matcher.quoteReplacement("\\\\"), -2); // (note that it's important to use the 2-argument version // of String.split(), and set the limit argument to a // negative value; otherwise any trailing backslashes // are lost.) for (int i = 0; i < splitTokens.length; i++) { splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\""); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r"); }// ww w.j a va 2 s.co m // TODO: // Make (some of?) the above optional; for ex., we // do need to restore the newlines when calculating UNFs; // But if we are subsetting these vectors in order to // create a new tab-delimited file, they will // actually break things! -- L.A. Jul. 28 2014 line[column] = StringUtils.join(splitTokens, '\\'); retVector[caseIndex] = line[column]; } } else { scanner.close(); throw new RuntimeException("Tab file has fewer rows than the stored number of cases!"); } } int tailIndex = numCases; while (scanner.hasNext()) { String nextLine = scanner.next(); if (!"".equals(nextLine)) { scanner.close(); throw new RuntimeException( "Column " + column + ": tab file has more nonempty rows than the stored number of cases (" + numCases + ")! current index: " + tailIndex + ", line: " + nextLine); } tailIndex++; } scanner.close(); return retVector; }
From source file:com.mss.tpo.payload.PayloadServiceImpl.java
public String reprocessPayloadData(String loginId, String inputPath, int id, String direction, String outputPath, String path) throws ServiceLocatorException { int processCount = 0; String responseString = ""; String reprocessPayloadQuery = ""; Timestamp curdate = DateUtility.getInstance().getCurrentDB2Timestamp(); try {/*from w w w.j a va 2 s .co m*/ connection = ConnectionProvider.getInstance().getConnection(); if ("Outbound".equalsIgnoreCase(direction)) { if (inputPath.contains("/")) { inputPath = inputPath.replaceAll("/", Matcher.quoteReplacement(File.separator)); System.out.println("inputPath-->" + inputPath); } String filePath = inputPath.substring(0, inputPath.lastIndexOf("\\")); String fileName = inputPath.substring(((inputPath.lastIndexOf("\\")) + 1), inputPath.length()); reprocessPayloadQuery = ("UPDATE MSCVP.TPO_PAYLOAD SET STATUS_FLAG = ?, FILE_NAME = ?, PATH = ?, MODIFIED_BY = ?, MODIFIED_TS = ? WHERE ID = " + id); preparedStatement = connection.prepareStatement(reprocessPayloadQuery); preparedStatement.setString(1, ""); preparedStatement.setString(2, fileName); preparedStatement.setString(3, filePath); preparedStatement.setString(4, loginId); preparedStatement.setTimestamp(5, curdate); processCount = processCount + preparedStatement.executeUpdate(); } else if ("Inbound".equalsIgnoreCase(direction)) { if ((!"".equalsIgnoreCase(inputPath)) && (!"".equalsIgnoreCase(path))) { if (inputPath.contains("/")) { inputPath = inputPath.replaceAll("/", Matcher.quoteReplacement(File.separator)); System.out.println("inputPath-->" + inputPath); } File sorceFile = new File(inputPath); File destFile = new File(path); destFile.mkdir(); String fileName1 = inputPath.substring(((inputPath.lastIndexOf("\\")) + 1), inputPath.length()); File theFile = new File(destFile.getAbsolutePath(), fileName1); FileUtils.copyFile(sorceFile, theFile); reprocessPayloadQuery = ("UPDATE MSCVP.TPO_PAYLOAD SET STATUS_FLAG = ?, MODIFIED_BY = ?, MODIFIED_TS = ? WHERE ID = " + id); preparedStatement = connection.prepareStatement(reprocessPayloadQuery); preparedStatement.setString(1, ""); preparedStatement.setString(2, loginId); preparedStatement.setTimestamp(3, curdate); processCount = processCount + preparedStatement.executeUpdate(); } } if (processCount > 0) { responseString = "<font color='green'>Reprocess successful.</font>"; } else { responseString = "<font color='green'>Paths are not provided or incorrect.</font>"; } } catch (Exception e) { responseString = "<font color='red'>Please try again!</font>"; } finally { try { if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException se) { se.printStackTrace(); throw new ServiceLocatorException(se); } } return responseString; }
From source file:gtu._work.ui.RegexReplacer.java
/** * @param fromPattern//from w w w. j a v a 2s. co m * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ String replacer(String fromPattern, String toFormat, String replaceText) { String errorRtn = replaceText.toString(); try { int patternFlag = 0; // if (multiLineCheckBox.isSelected()) { patternFlag = Pattern.DOTALL | Pattern.MULTILINE; } Pattern pattern = Pattern.compile(fromPattern, patternFlag); Matcher matcher = pattern.matcher(replaceText); StringBuffer sb = new StringBuffer(); String tempStr = null; TradeOffConfig config = this.getTradeOffConfig(); { int startPos = 0; for (; matcher.find();) { tempStr = toFormat.toString(); sb.append(replaceText.substring(startPos, matcher.start())); // ---------------------------------------------- if (StringUtils.isBlank(config.fremarkerKey)) { // regex for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); } } else if (StringUtils.isNotBlank(config.fremarkerKey)) { // freemarker Map<String, Object> root = new HashMap<String, Object>(); TreeMap<Integer, Object> lstMap = new TreeMap<Integer, Object>(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { lstMap.put(ii, matcher.group(ii)); } root.put(StringUtils.trimToEmpty(config.fremarkerKey), lstMap.values()); System.out.println("template Map : " + root); tempStr = FreeMarkerSimpleUtil.replace(tempStr, root); } // ---------------------------------------------- sb.append(tempStr); startPos = matcher.end(); } sb.append(replaceText.substring(startPos)); } return sb.toString(); } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); return errorRtn; } }
From source file:org.freeplane.view.swing.features.time.mindmapmode.NodeList.java
private void replace(final IReplaceInputInformation info) { final String searchString = (String) mFilterTextSearchField.getSelectedItem(); if (searchString == null) return;//from w w w. j av a2 s . c o m final String replaceString = (String) mFilterTextReplaceField.getSelectedItem(); Pattern p; try { p = Pattern.compile(useRegexInFind.isSelected() ? searchString : Pattern.quote(searchString), matchCase.isSelected() ? 0 : Pattern.CASE_INSENSITIVE); } catch (final PatternSyntaxException e) { UITools.errorMessage(TextUtils.format("wrong_regexp", searchString, e.getMessage())); return; } final String replacement = replaceString == null ? "" : replaceString; final int length = info.getLength(); for (int i = 0; i < length; i++) { final NodeHolder nodeHolder = info.getNodeHolderAt(i); final String text = nodeHolder.node.getText(); final String replaceResult; final String literalReplacement = useRegexInReplace.isSelected() ? replacement : Matcher.quoteReplacement(replacement); try { if (HtmlUtils.isHtmlNode(text)) { replaceResult = NodeList.replace(p, text, literalReplacement); } else { replaceResult = p.matcher(text).replaceAll(literalReplacement); } } catch (Exception e) { UITools.errorMessage(TextUtils.format("wrong_regexp", replacement, e.getMessage())); return; } if (!StringUtils.equals(text, replaceResult)) { info.changeString(nodeHolder, replaceResult); } } timeTableModel.fireTableDataChanged(); mFlatNodeTableFilterModel.resetFilter(); mFilterTextSearchField.insertItemAt(mFilterTextSearchField.getSelectedItem(), 0); mFilterTextReplaceField.insertItemAt(mFilterTextReplaceField.getSelectedItem(), 0); mFilterTextSearchField.setSelectedItem(""); }