List of usage examples for java.util.regex Matcher replaceAll
public String replaceAll(Function<MatchResult, String> replacer)
From source file:com.gewara.util.XSSFilter.java
protected String regexReplace(String regex_pattern, String replacement, String s) { Pattern p = Pattern.compile(regex_pattern); Matcher m = p.matcher(s); return m.replaceAll(replacement); }
From source file:com.dmsl.anyplace.SearchPOIActivity.java
private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // get the search type mSearchType = (SearchTypes) intent.getSerializableExtra("searchType"); if (mSearchType == null) finishSearch("No search type provided!", null); // get the query string final String query = intent.getStringExtra("query"); double lat = intent.getDoubleExtra("lat", 0); double lng = intent.getDoubleExtra("lng", 0); AnyplaceSuggestionsTask mSuggestionsTask = new AnyplaceSuggestionsTask( new AnyplaceSuggestionsTask.AnyplaceSuggestionsListener() { @Override// w ww. j a va 2 s.c om public void onSuccess(String result, List<? extends IPoisClass> pois) { // we have pois to query for a match mQueriedPoisStr = new ArrayList<Spanned>(); mQueriedPois = pois; // Display part of Description Text Only // Make an approximation of available space based on map size final int viewWidth = (int) (findViewById(R.id.txtResultsFound).getWidth() * 2); View infoWindow = getLayoutInflater() .inflate(R.layout.queried_pois_item_1_searchactivity, null); TextView infoSnippet = (TextView) infoWindow; TextPaint paint = infoSnippet.getPaint(); // Regular expression // ?i ignore case Pattern pattern = Pattern.compile(String.format("((?i)%s)", query)); for (IPoisClass pm : pois) { String name = "", description = ""; Matcher m; m = pattern.matcher(pm.name()); // Makes matched query bold using HTML format // $1 returns the regular's expression outer parenthesis value name = m.replaceAll("<b>$1</b>"); m = pattern.matcher(pm.description()); if (m.find()) { // Makes matched query bold using HTML format // $1 returns the regular's expression outer parenthesis value int startIndex = m.start(); description = m.replaceAll("<b>$1</b>"); description = AndroidUtils.fillTextBox(paint, viewWidth, description, startIndex + 3); } mQueriedPoisStr.add(Html.fromHtml(name + "<br>" + description)); } ArrayAdapter<Spanned> mAdapter = new ArrayAdapter<Spanned>( // getBaseContext(), R.layout.queried_pois_item_1, getBaseContext(), R.layout.queried_pois_item_1_searchactivity, mQueriedPoisStr); lvResultPois.setAdapter(mAdapter); txtResultsFound.setText("Results found [ " + mQueriedPoisStr.size() + " ]"); } @Override public void onErrorOrCancel(String result) { // no pois exist finishSearch("No Points of Interest exist!", null); } @Override public void onUpdateStatus(String string, Cursor cursor) { SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.queried_pois_item_1_searchactivity, cursor, new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1 }, new int[] { android.R.id.text1 }); lvResultPois.setAdapter(adapter); txtResultsFound.setText("Results found [ " + cursor.getCount() + " ]"); } }, this, mSearchType, new GeoPoint(lat, lng), query); mSuggestionsTask.execute(); } }
From source file:org.cfeclipse.cfml.frameworks.actions.BaseAction.java
/** * Parses listfiles("path","relative or absolute", "delimiter"); * @param actionText/*ww w. ja v a2 s .c om*/ * @return */ private String doListFileFunctions(String actionText) { String functionMatch = "listfiles\\s*\\(\\s*\"([^\"]*)\"\\s*,\\s*\"([^\"]*)\",\\s*\"([^\"]*)\"\\)"; //listfiles\s*\(\s*"([^"]*)"\s*,\s*"([^"]*)",\s*"([^"]*)"\) Pattern pattern = Pattern.compile(functionMatch); Matcher matcher = pattern.matcher(actionText); while (matcher.find()) { String path = matcher.group(1); String type = matcher.group(2); String delimiter = matcher.group(3); String files = doListFile(path, type, delimiter); actionText = matcher.replaceAll(files); } return null; }
From source file:org.bbaw.pdr.ae.view.identifiers.internal.ConcurrenceSearchController.java
private String requestWebService(URL url) throws URISyntaxException, UnsupportedEncodingException { String result = null;//www.j ava2s .com if (url != null) { HttpClient client = new HttpClient(); // System.out.println("url " + url.toString()); // PostMethod method = null; HttpClient httpclient = null; httpclient = new HttpClient(); String urlString = new String(url.toString()); if (urlString.contains(" ")) { // System.out.println("containts ws"); urlString.replace(" ", "%20"); } Pattern p = Pattern.compile("\\s"); Matcher m = p.matcher(urlString); // while (m.find()) // { // // System.out.println("\\s"); // } urlString = m.replaceAll("%20"); // while (m.find()) // { // System.out.println("2.\\s"); // } // urlString = URLEncoder.encode(urlString, "UTF-8"); // urlString.replace("\\s+", "%20"); GetMethod get = new GetMethod(urlString); HostConfiguration hf = new HostConfiguration(); hf.setHost(urlString, url.getPort()); httpclient.setHostConfiguration(hf); // get = new PostMethod(theURL); // LogHelper.logMessage("Before sending SMS Message: "+message); int respCode; try { respCode = httpclient.executeMethod(get); log = new Status(IStatus.INFO, Activator.PLUGIN_ID, "Response code: " + respCode); iLogger.log(log); // successful. /* send request */ final int status = client.executeMethod(get); // LOG.debug("http status #execute: " + // Integer.toString(status)); switch (status) { case HttpStatus.SC_NOT_IMPLEMENTED: get.releaseConnection(); // throw new IOException("Solr Query #GET (" + // get.getURI().toString() + ") returned 501"); default: result = get.getResponseBodyAsString(); get.releaseConnection(); } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }
From source file:org.apache.hadoop.chukwa.dataloader.MetricDataLoader.java
private String escape(String s, String c) { String ns = s.trim();/*w ww .ja va2 s.co m*/ Pattern pattern = Pattern.compile(" +"); Matcher matcher = pattern.matcher(ns); String s2 = matcher.replaceAll(c); return s2; }
From source file:esg.node.components.notification.ESGNotifier.java
private boolean generateNotification(NotificationDAO.NotificationRecipientInfo nri) { Matcher matcher = null; String messageText = ""; //NOTE: This is a two pass replacement... This could //probably be done more elegantly in one, read up more //about regex and make it happen. matcher = userid_pattern.matcher(messageTemplate); String tmp = matcher.replaceAll(nri.userid); matcher = update_info_pattern.matcher(tmp); messageText = matcher.replaceAll(nri.toString()); return sendNotification(nri.userid, nri.userAddress, messageText); }
From source file:de.jcup.egradle.sdk.builder.action.javadoc.ReplaceJavaDocPartsAction.java
License:asdf
String handleTypeLinksWithoutType(String replacedJavaDocParts, Type parentType) { if (parentType == null) { throw new IllegalStateException("no parent type!"); }//from w w w.j a va 2 s .c o m if (replacedJavaDocParts == null) { return null; } if (replacedJavaDocParts.indexOf(TYPE_PREFIX_WITHOUT_TYPE) == -1) { return replacedJavaDocParts; } String typeName = parentType.getName(); Matcher matcher = PATTERN_TYPE_PREFIX_WITHOUT_TYPE.matcher(replacedJavaDocParts); replacedJavaDocParts = matcher.replaceAll(DSLConstants.HYPERLINK_TYPE_PREFIX + typeName + "#"); return replacedJavaDocParts; }
From source file:org.cfeclipse.cfml.frameworks.actions.BaseAction.java
/** * @param actionText//from w w w . j a va 2 s . co m * @return */ private String doFwFilePath(String actionText) { String functionMatch = "fwfilepath\\(\\)"; Pattern pattern = Pattern.compile(functionMatch); Matcher matcher = pattern.matcher(actionText); IPath projectRelativePath = this.treeNode.getFrameworkFile().getFile().getProjectRelativePath(); IPath path2 = projectRelativePath.removeLastSegments(1); while (matcher.find()) { String path = matcher.group(0); actionText = matcher.replaceAll(path2.toOSString()); } return actionText; }
From source file:org.kevinferrare.solarSystemDataRetriever.jplhorizons.parser.JplHorizonsDataParser.java
/** * Parses the given data from the JPL HORIZONS system.<br /> * As the data format is not coherent over files (they seem to be written by hand for the physical data section), * the parser has to handle a lot of special cases and cannot be guaranteed to work on untested files.<br /> * When mass or density cannot be found / parsed, their value is set to -1 * // w w w.j ava2 s . c o m * @param jplId * the id of the object for which to parse the data * @param rawGravityObjectData * string containing the response from the JPL HORIZONS system for this object * @return a GravityObject filled with data * @throws Exception */ public GravityObject parseGravityObjectInfos(String jplId, String rawGravityObjectData) throws Exception { try { Map<String, String> objectPropertiesMap = parseKeyValues(rawGravityObjectData); if (objectPropertiesMap == null) { return null; } GravityObject gravityObject = new GravityObject(); gravityObject.setId(jplId); // some items don't have those fields, set a default value gravityObject.setDensity(-1); gravityObject.setMass(-1); gravityObject.setType(null); for (Entry<String, String> entry : objectPropertiesMap.entrySet()) { String key = entry.getKey().toLowerCase(); String value = entry.getValue(); if (value.isEmpty()) { continue; } if (key.contains("mass ") && (key.contains(" g") || key.contains(" kg")) || value.contains(" kg")) {// for example Mass (10^24 kg) // a lot of entries have the multiplier in the key ... // key : Mass, 10^20 kg Matcher matcher = replaceNonAlphanumericPattern.matcher(key); key = matcher.replaceAll(""); // key : Mass10^20kg matcher = massKeyMultiplierExtractPattern.matcher(key); double keyMultiplier = 1; if (matcher.find() && matcher.groupCount() == 2) { keyMultiplier = Math.pow(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))); } if (!key.contains("kg") && key.contains("g") && !key.contains("weight")) { keyMultiplier *= 0.001;// convert grams in kilograms } if (value.contains("lb")) { keyMultiplier *= 0.45359237; } // value can be "1.08+-0.1 (10^-4)" (second multiplier) ... matcher = massValueImprecisionRemovePattern.matcher(value); value = matcher.replaceAll(""); matcher = massValueExtractPattern.matcher(value); if (matcher.find()) { double mass = Double.parseDouble(matcher.group(1)) * keyMultiplier; String multiplierNumber = matcher.group(3); String multiplierExponent = matcher.group(4); if (multiplierNumber != null && multiplierExponent != null) { mass *= Math.pow(Integer.parseInt(multiplierNumber), Integer.parseInt(multiplierExponent)); } gravityObject.setMass(Math.floor(mass + 0.5d)); } } if (key.toLowerCase().contains("launch mass")) {// spacecrafts // Total launch mass = 1223 kg // Launch Mass: 4 tonnes double mass = Double.parseDouble(value.split(" +")[0]); if (value.toLowerCase().contains("ton")) { mass *= 1000;// tons->kg } gravityObject.setMass(Math.floor(mass + 0.5d)); } if ("gm".equals(key)) { try { double gm = Double.parseDouble(value); gm = gm * Math.pow(10, 20) / 6.6725985; gravityObject.setMass(Math.floor(gm + 0.5d)); } catch (NumberFormatException ex) { } } if (key.contains("density")) { double density = Double.parseDouble(stripImprecisionData(value.split(" +")[0].split("\\(")[0])); gravityObject.setDensity(density * 1000);// convert to kg/m3 } if ("name".equals(key)) { gravityObject.setName(value); } if ("coordinates".equals(key)) { String[] split = value.split(","); gravityObject.setX(Double.parseDouble(split[2].trim()) * 1000);// km to m gravityObject.setY(Double.parseDouble(split[3].trim()) * 1000); gravityObject.setZ(Double.parseDouble(split[4].trim()) * 1000); gravityObject.setVx(Double.parseDouble(split[5].trim()) * 1000); gravityObject.setVy(Double.parseDouble(split[6].trim()) * 1000); gravityObject.setVz(Double.parseDouble(split[7].trim()) * 1000); } if ("objectType".equals(key)) { if ("spacecraft".equals(value)) { gravityObject.setType(GravityObjectType.SPACECRAFT); } } } //use additional data if available if (additionalData != null) { GravityObject additional = additionalData.get(jplId); if (additional != null) { gravityObject.setMass(additional.getMass()); gravityObject.setDensity(additional.getDensity()); } } // determine the type if (gravityObject.getType() == null) { gravityObject.setType(determineType(gravityObject, jplId)); } return gravityObject; } catch (Exception ex) { throw new Exception(rawGravityObjectData, ex); } }
From source file:de.appsolve.padelcampus.admin.controller.general.AdminGeneralModulesController.java
private void rewriteLinks(Module model) { if (model.getId() != null) { Module existingModule = moduleDAO.findById(model.getId()); if (!model.getUrlTitle().equals(existingModule.getUrlTitle())) { String oldHref = String.format("href=\"(%s|/page%s)\"", existingModule.getUrl(), existingModule.getUrl()); String newHref = String.format("href=\"%s\"", model.getUrl()); Pattern p = Pattern.compile(oldHref, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); for (PageEntry pageEntry : pageEntryDAO.findAll()) { String message = pageEntry.getMessage(); if (!StringUtils.isEmpty(message)) { Matcher m = p.matcher(message); if (m.find()) { LOG.info(String.format("replacing links %s by %s in page entry %s", oldHref, newHref, pageEntry.getId())); pageEntry.setMessage(m.replaceAll(newHref)); pageEntryDAO.saveOrUpdate(pageEntry); }//from w w w . j a v a2 s .com } } } } }