List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:org.openmrs.module.formentry.PublishInfoPath.java
/** * Scans an XSL file for HL7 concept specifications, appending the appropriate concept-name * specification.//from w ww. ja v a 2 s .c om * * @param xslFilename */ public static void appendConceptnamesInXsl(String xslFilename, File tempDir) throws IOException { ConceptService cs = Context.getConceptService(); Locale defaultLocale = Context.getLocale(); try { File xslFile = new File(tempDir.getAbsolutePath(), xslFilename); File tmpXslFile = File.createTempFile("infopath", ".xsltmp", tempDir); BufferedReader xslReader = new BufferedReader(new FileReader(xslFile)); PrintWriter tmpXslWriter = new PrintWriter(new FileWriter(tmpXslFile)); String line = xslReader.readLine(); while (line != null) { Matcher m = hl7ConceptNamePattern.matcher(line); if (m.find()) { 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); } } else { tmpXslWriter.println(line); line = xslReader.readLine(); } } tmpXslWriter.close(); xslReader.close(); xslFile.delete(); if (!tmpXslFile.renameTo(xslFile)) { throw new IOException("Unable to rename xsl file from " + tmpXslFile.getAbsolutePath() + " to " + xslFile.getAbsolutePath()); } } catch (FileNotFoundException e) { log.error("update of concept names in \"" + xslFilename + "\" failed, because: " + e); e.printStackTrace(); } catch (IOException e) { log.error("update of concept names in \"" + xslFilename + "\" failed, because: " + e); e.printStackTrace(); } }
From source file:chatbot.Chatbot.java
/** ************************************************************************************************** * Remove punctuation and contractions from a sentence. * @return the sentence in a String minus these elements. *//*from w w w . j a v a 2 s . com*/ public String removePunctuation(String sentence) { Matcher m = null; if (isNullOrEmpty(sentence)) return sentence; m = Pattern.compile("(\\w)\\'re").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)\\'m").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)n\\'t").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)\\'ll").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)\\'s").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)\\'d").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } m = Pattern.compile("(\\w)\\'ve").matcher(sentence); while (m.find()) { //System.out.println("matches"); String group = m.group(1); sentence = m.replaceFirst(group).toString(); m.reset(sentence); } sentence = sentence.replaceAll("\\'", ""); sentence = sentence.replaceAll("\"", ""); sentence = sentence.replaceAll("\\.", ""); sentence = sentence.replaceAll("\\;", ""); sentence = sentence.replaceAll("\\:", ""); sentence = sentence.replaceAll("\\?", ""); sentence = sentence.replaceAll("\\!", ""); sentence = sentence.replaceAll("\\, ", " "); sentence = sentence.replaceAll("\\,[^ ]", ", "); sentence = sentence.replaceAll(" ", " "); return sentence; }
From source file:org.jtree.core.JTreeMap.java
/** * Get the parent-list of a key// ww w . j a va2 s.c om * if key is list1:list2:list3 it will return list1:list2 * its private until I see some benefit to make it public * @param key * @return returns string before the last delimiter */ private String getParentDirectory(String key) { if (!key.contains(delimiter)) { return ":"; } Matcher match = listPattern.matcher(key); String parentDirectory = match.replaceFirst(""); if (parentDirectory.equals("")) { return this.delimiter; } return parentDirectory; }
From source file:org.jtree.core.JTreeMap.java
/** * Get the last sibling child of a key/*from w ww . j av a2 s. c o m*/ * if key is list1:list2:list3 it will return list3 * its private unil I see som benefit to make it public * @param key * @return the last entry after the last delimiter */ private String getChildKey(String key) { if (key == null) { logger.warn("key " + key + " is null?! "); return ""; } if (key.equals("")) { logger.warn("key " + key + " is empty?! "); return ""; } if (!key.contains(this.delimiter)) { logger.debug("key " + key + " is root! "); return ""; } Matcher match = childPattern.matcher(key); String childKey = match.replaceFirst(""); return childKey; }
From source file:org.apache.zeppelin.display.Input.java
public static String getSimpleQuery(Map<String, Object> params, String script) { String replaced = script;/*from w w w. j av a 2 s. c o m*/ Matcher match = VAR_PTN.matcher(replaced); while (match.find()) { Input input = getInputForm(match); Object value; if (params.containsKey(input.name)) { value = params.get(input.name); } else { value = input.defaultValue; } String expanded; if (value instanceof Object[] || value instanceof Collection) { // multi-selection String delimiter = input.argument; if (delimiter == null) { delimiter = DEFAULT_DELIMITER; } Collection<Object> checked = value instanceof Collection ? (Collection<Object>) value : Arrays.asList((Object[]) value); List<Object> validChecked = new LinkedList<>(); for (Object o : checked) { // filter out obsolete checked values for (ParamOption option : input.getOptions()) { if (option.getValue().equals(o)) { validChecked.add(o); break; } } } params.put(input.name, validChecked); expanded = StringUtils.join(validChecked, delimiter); } else { // single-selection expanded = value.toString(); } replaced = match.replaceFirst(expanded); match = VAR_PTN.matcher(replaced); } return replaced; }
From source file:org.kuali.rice.core.impl.config.property.JAXBConfigImpl.java
/** * This method parses the value string to find all nested properties (foo=${nested}) and * replaces them with the value returned from calling resolve(). It does this in a new string * and does not modify the raw or resolved properties objects. * // w w w. j a v a2s. c o m * @param value the string to search for nest properties * @param keySet contains all keys used so far in this recursion. used to check for circular * references. * @return */ protected String parseValue(String value, Set<String> keySet) { String result = value; Matcher matcher = pattern.matcher(value); while (matcher.find()) { // get the first, outermost ${} in the string. removes the ${} as well. String key = matcher.group(1); String resolved = resolve(key, keySet); result = matcher.replaceFirst(Matcher.quoteReplacement(resolved)); matcher = matcher.reset(result); } return result; }
From source file:org.deeplearning4j.nn.modelimport.keras.KerasModel.java
/** * Store weights to import with each associated Keras layer. * * @param weightsArchive Hdf5Archive/* ww w .ja va 2s . c o m*/ * @param weightsRoot * @throws InvalidKerasConfigurationException */ protected void helperImportWeights(Hdf5Archive weightsArchive, String weightsRoot) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { List<String> layerGroups = weightsRoot != null ? weightsArchive.getGroups(weightsRoot) : weightsArchive.getGroups(); /* Set weights in KerasLayer for each entry in weights map. */ for (String layerName : layerGroups) { List<String> layerParamNames = weightsRoot != null ? weightsArchive.getDataSets(weightsRoot, layerName) : weightsArchive.getDataSets(layerName); if (layerParamNames.isEmpty()) continue; if (!layerParamNames.isEmpty() && !this.layers.containsKey(layerName)) throw new InvalidKerasConfigurationException( "Found weights for layer not in model (named " + layerName + ")"); KerasLayer layer = this.layers.get(layerName); if (layerParamNames.size() != layer.getNumParams()) throw new InvalidKerasConfigurationException( "Found " + layerParamNames.size() + " weights for layer with " + layer.getNumParams() + " trainable params (named " + layerName + ")"); Map<String, INDArray> weights = new HashMap<String, INDArray>(); for (String layerParamName : layerParamNames) { /* TODO: push this logic into KerasLayer subclasses. Layers know what * parameters they have and should be looking for, so let them handle * it in a layer-specific manner. */ /* Keras parameter names are typically formatted as [layer name]_[parameter]. For * example, the weight matrix in the first Dense layer with the TensorFlow backend * will be named "dense_1_W:0." */ Matcher layerNameMatcher = Pattern.compile(layerName).matcher(layerParamName); if (!layerNameMatcher.find()) throw new InvalidKerasConfigurationException( "Unable to parse layer/parameter name " + layerParamName + " for stored weights."); String paramName = layerNameMatcher.replaceFirst(""); /* Usually layer name is separated from parameter name by an underscore. */ Matcher paramNameMatcher = Pattern.compile("^_(.+)$").matcher(paramName); if (paramNameMatcher.find()) paramName = paramNameMatcher.group(1); /* TensorFlow backend often appends ":" followed by one or more digits to parameter * names. We strip it off here. */ Matcher tfSuffixMatcher = Pattern.compile(":\\d+?$").matcher(paramName); if (tfSuffixMatcher.find()) paramName = tfSuffixMatcher.replaceFirst(""); /* TensorFlow backend also may append "_" followed by one or more digits to parameter * names. We strip it off here. */ Matcher tfParamNbMatcher = Pattern.compile("_\\d+$").matcher(paramName); if (tfParamNbMatcher.find()) paramName = tfParamNbMatcher.replaceFirst(""); INDArray paramValue = weightsRoot != null ? weightsArchive.readDataSet(layerParamName, weightsRoot, layerName) : weightsArchive.readDataSet(layerParamName, layerName); weights.put(paramName, paramValue); } layer.setWeights(weights); } /* Look for layers in model with no corresponding entries in weights map. */ Set<String> layerNames = new HashSet<String>(this.layers.keySet()); layerNames.removeAll(layerGroups); for (String layerName : layerNames) { if (this.layers.get(layerName).getNumParams() > 0) throw new InvalidKerasConfigurationException( "Could not find weights required for layer " + layerName); } }
From source file:com.celamanzi.liferay.portlets.rails286.BodyTagVisitor.java
/** * Recurses to every HTML tag./*from w ww . j ava 2s. c o m*/ * This function converts the hyperlinks to parameters in the portletUrl. * The RenderFilter picks this parameter, stores it to session and launches an * http request. GET works fine, POST has some problems. * * It is possible to escape the portlet link by adding "exit_portlet=true" * to the HTTP request parameters. (www.example.com?exit_portlet=true) */ public void visitTag(Tag tag) { //log.debug("Encountered a " + tag.getClass()); // Floods the debug channel RouteAnalyzer ra = new RouteAnalyzer(baseUrl, servlet); Pattern pattern = null; Matcher matcher = null; /** * Replace the <body> tag with <div id=%namespace%_body> */ if (tag instanceof BodyTag) { BodyTag b = (BodyTag) tag; String id = namespace + "_body"; // also defined in HeadProcessor() log.debug("Replacing <body> with <div id=" + id + ">"); b.setTagName("div"); b.getEndTag().setTagName("/div"); b.setAttribute("id", "\"" + id + "\""); // damn, htmlparser does not produce clean XHTML } /** * Convert links ###(, only if portletUrl is defined). * - PortletURL is not available while "testing". * - skip if parameter 'exit_portlet=true'. */ // else if ((tag instanceof LinkTag) && (portletUrl != null)) else if (tag instanceof LinkTag) { LinkTag link = (LinkTag) tag; PortletURL newHref = portletUrl; /** HTTP */ if ((link.isHTTPLink()) && (!link.getLink().equals(""))) { log.debug("Encountered a HTTPLink: " + link.getLink()); String href = link.getAttribute("href"); String route = null; String onclick = null; String newLink = null; /** Ajax */ // links with href="#" and onclick="new Ajax.Updater" pattern = Pattern.compile("^#$"); matcher = pattern.matcher(href); if (matcher.find()) { /* Prototype: <a onclick="new Ajax.Updater('result', '/caterpillar/test_bench/xhr/get_time', {asynchronous:true, evalScripts:true}); return false;" href="#"> */ onclick = (String) link.getAttribute("onclick"); if (onclick != null) { log.debug("onclick: " + onclick); Pattern ajax_pattern = Pattern.compile("Ajax.Updater\\(([^\\)]*)"); Matcher ajax_matcher = ajax_pattern.matcher(onclick); if (ajax_matcher.find()) { // 'result', '/caterpillar/test_bench/xhr/get_time', {asynchronous:true, evalScripts:true} String[] ajax = ajax_matcher.group(1).split(", "); // /caterpillar/test_bench/xhr/get_time String ajax_url = ajax[1].substring(1, ajax[1].length() - 1); log.debug("Ajax url: " + ajax_url); resourceUrl.setParameter("railsRoute", ajax_url); // <a onclick="new Ajax.Updater('result', 'http://liferay-resource-url?route=/ajax_url', .... onclick = onclick.replaceFirst(ajax_url, resourceUrl.toString()); log.debug("new onclick: " + onclick); link.setAttribute("onclick", onclick); } } else { log.warn("Unknown type JavaScript link passed: " + link.toHtml()); } return; } // the link might be plain "some_file.htm(l)", // that will raise MalformedURLException. String local_file = "^[a-zA-Z0-9_%]*.htm"; pattern = Pattern.compile(local_file); matcher = pattern.matcher(href); if (matcher.find()) { log.debug("Protocolless URL: " + href); href = baseUrl + href; } /** * Exiting portlet? * * - check if the parameter 'exit_portlet' is 'true'. * => return the link as such, ie. not wrapped in PortletURL. */ String exit_param = "exit_portlet=(true|false)"; pattern = Pattern.compile(exit_param); matcher = pattern.matcher(href); if (matcher.find()) { log.debug("Exit portlet parameter encountered: " + exit_param); // TODO: use a proper replace regexp, so sanitization is not required. href = href.replaceFirst(exit_param, ""); // remove the parameter href = href.replaceFirst("&$", ""); // sanitize href = href.replaceFirst("\\?&", "?"); // sanitize href = href.replaceFirst("\\?$", ""); // sanitize log.debug("Saving link: " + href); link.setLink(href); /** URL -> PortletURL */ } else { /** onclick javascript */ if (link.getAttribute("onclick") != null) { log.debug("Onclick attribute detected"); onclick = link.getAttribute("onclick"); //log.debug(onclick); pattern = Pattern.compile("document.createElement('form')"); matcher = pattern.matcher(onclick); log.debug("Onclick creates a form"); /** Replaces the onclick JavaScript's action URL to portlet actionUrl, and sets the originalActionUrl parameter. * This is handled in processAction(). * Some repetition with the regular HTML form handler (in this one giant function). */ if (actionUrl != null) { log.debug("Replacing onclick url with actionUrl"); // add originalActionUrl to form parameters by adding an input // element to the page. String js = null; try { js = "var inp=document.createElement(\"input\");inp.name='originalActionUrl';inp.value='" + ra.getRequestRoute(href) + "';f.appendChild(inp);"; } catch (java.net.MalformedURLException e) { log.error(e.getMessage()); } //log.debug(js); // alter the onClick onclick = onclick.replaceFirst("this.href", "'" + actionUrl.toString() + "'") .replaceFirst("f.submit", js + "f.submit"); // set the new link log.debug("Setting the onclick attribute to the new link"); link.setAttribute("onclick", onclick); log.debug(onclick); newLink = "#"; } // onclick /** Extract the Rails route */ } else { try { route = ra.getRequestRoute(href); // prevent parameter separator '&' from being sent as &amp; route = route.replaceAll("&", "&"); } catch (java.net.MalformedURLException e) { log.error(e.getMessage()); } } // route /** Strip target. * If there is a target, the browser will open a new tab (or an instance) and fail to convert links on that page */ String target = link.getAttribute("target"); if (target != null) { log.debug("Removing the target attribute \"" + target + "\""); link.removeAttribute("target"); } /** Change the link XXX: was absolute path checking made for download feature? Rails can also have a hard link... */ //if (!RouteAnalyzer.isAbsolutePath(route) && portletUrl != null) { if (portletUrl != null) { if (route != null) { //Clear scheme + location Pattern url_pattern = Pattern.compile("^https?://[^/]*"); Matcher url_matcher = url_pattern.matcher(route); if (url_matcher.find()) { log.debug("absolute url - reverting to default host"); route = url_matcher.replaceFirst(""); } newHref.setParameter("railsRoute", route); log.debug("Added parameter railsRoute to the PortletURL: " + route); newLink = newHref.toString(); } log.debug("Replacing the original link tag to: " + newLink); link.setLink(newLink); } else { log.debug("portletUrl is null"); } } } // exit portlet? /* else if (link.isEndTag()) { log.debug("Link end tag detected -- where is the begin tag? This is a bug."); log.debug(tag.getText()); }*/ else if (link.isHTTPSLink()) { log.warn("Cannot handle HTTPS links yet"); } //else if (link.isJavascriptLink()) { log.warn("Cannot handle JavaScript links yet"); } else if (link.isMailLink()) { log.debug("No changes to mail links"); } else if (link.isFTPLink()) { log.debug("No changes to FTP links"); } else if (link.isIRCLink()) { log.debug("No changes to IRC links"); } else { log.warn("fixme: Encountered an unknown link type: " + link.getLink()); } } /** * Convert images */ else if (tag instanceof ImageTag) { ImageTag img = (ImageTag) tag; String src = img.getImageURL(); java.net.URL srcUrl = null; // break if the source is an external image if (isExternal(src)) { log.debug("Preserving image " + src); return; } /* If the src should be translated: * 1) check if the src is absolute or relative * 2) if absolute => add baseUrl prefix * 3) if relative => add baseUrl + documentPath prefix */ String path = ""; // TODO: move RouteAnalyzer up here // HACK: lookout for http, let RouteAnalyzer do this Pattern rel_link_pattern = Pattern.compile("^http"); Matcher rel_link_matcher = rel_link_pattern.matcher(src); if (rel_link_matcher.find()) { log.debug(src + " is already a full URL, preserving"); return; } log.debug("Converting image " + src); // test if the src begins with slash '/' rel_link_pattern = Pattern.compile("^/"); rel_link_matcher = rel_link_pattern.matcher(src); if (!rel_link_matcher.find()) { log.debug("The image path \"" + src + "\" is relative"); path += '/'; } else { log.debug("The image path \"" + src + "\" is absolute"); } path += src; String url = null; try { url = ra.getFullURL(path).toString(); } catch (java.net.MalformedURLException e) { log.error(e.getMessage()); return; } log.debug("New image URL: " + url); img.setImageURL(url); } /** * Convert forms, only if actionUrl is defined */ else if (tag instanceof FormTag) { if (actionUrl == null) { log.warn("Form action cannot be manipulated - portlet actionURL is null"); return; } FormTag frm = (FormTag) tag; String method = frm.getFormMethod(); //String formAction = frm.extractFormLocn(); String formAction = frm.getFormLocation(); log.debug("form " + method + " to action: " + formAction); //log.debug(frm.toString()); /** * Exiting portlet? * Yes, this is a duplicate from the LinkTag handling. * Not good, not good at all. */ String exit_param = "exit_portlet=(true|false)"; pattern = Pattern.compile(exit_param); matcher = pattern.matcher(formAction); if (matcher.find()) { log.debug("Exit portlet parameter encountered: " + exit_param); // TODO: use a proper replace regexp, so sanitization is not required. formAction = formAction.replaceFirst(exit_param, ""); // remove the parameter formAction = formAction.replaceFirst("&$", ""); // sanitize formAction = formAction.replaceFirst("\\?&", "?"); // sanitize formAction = formAction.replaceFirst("\\?$", ""); // sanitize log.debug("Saving form action: " + formAction); frm.setFormLocation(formAction); return; } /** RouteAnalyzer */ try { formAction = ra.getRequestRoute(formAction); } catch (java.net.MalformedURLException e) { log.error(e.getMessage()); } log.debug("Full action URL: " + formAction); if (method.equals("post") || method.equals("put")) { // replace the action URL with the portlet actionURL String portletAction = actionUrl.toString(); log.debug("New form action URL: " + portletAction); frm.setFormLocation(portletAction); // TODO: iterate all form tags and add namespace // create a new hidden tag that stores the original action url String newtag = "<div style=\"display: none;\">"; newtag += "<input name=\"" + namespace + "originalActionUrl" + "\" type=\"text\" size=\"0\" value=\"" + formAction + "\" />"; newtag += "<input name=\"" + namespace + "originalActionMethod" + "\" type=\"text\" size=\"0\" value=\"" + method + "\" />"; newtag += "</div>"; // get the children to add a new node into NodeList inputs = frm.getChildren(); try { Parser parser = new Parser(newtag); log.debug("Adding a new form child input tag: " + newtag); if (!newtag.equals("")) { inputs.add(parser.parse(null)); } } catch (ParserException pe) { log.error(pe.getMessage()); } frm.setChildren(inputs); } // other specific tags and generic TagNode objects } else { } }
From source file:me.Wundero.Ray.utils.TextUtils.java
private static String[] allmatches(final String a, final Pattern b) { String f = a;//from www . j av a2 s.c o m Matcher m = b.matcher(f); List<String> o = Utils.al(); while ((m = m.reset(f)).find()) { o.add(m.group()); f = m.replaceFirst(""); } return o.toArray(new String[o.size()]); }
From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioning.java
private String makeTimestamps(String where, Pattern pattern, String template, Map<String, Object> values) { String output = where;/*from w w w . jav a2s. c o m*/ Matcher matcher = pattern.matcher(output); int count = values.size(); while (matcher.matches()) { String property = matcher.group(2); Object value = matcher.group(4); if (property.equals("created") || property.equals("lastModified")) { try { value = TIMESTAMP_FORMAT.parse((String) value); } catch (ParseException e) { // ignore } } values.put("value" + count, value); String query = template.replace("?", "value" + count); output = matcher.replaceFirst( String.format(query, matcher.group(1), property, matcher.group(3), matcher.group(5))); matcher = pattern.matcher(output); count++; } return output; }