List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSFontFaceRule.java
/** * {@inheritDoc}/*from w w w . ja v a2 s . co m*/ */ @Override public String getCssText() { String cssText = super.getCssText(); final BrowserVersion browserVersion = getBrowserVersion(); if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_CRLF)) { cssText = StringUtils.replace(cssText, "{", "{\r\n\t"); cssText = StringUtils.replace(cssText, "}", ";\r\n}\r\n"); cssText = StringUtils.replace(cssText, "; ", ";\r\n\t"); } else if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_NO_CRLF)) { cssText = StringUtils.replace(cssText, "{", "{ "); cssText = StringUtils.replace(cssText, "}", "; }"); cssText = StringUtils.replace(cssText, "; ", "; "); final Matcher matcher = REPLACEMENT_2.matcher(cssText); matcher.find(); final String url = matcher.group(1); final HtmlPage page = (HtmlPage) ((CSSStyleSheet) getParentScope()).getWindow().getWebWindow() .getEnclosedPage(); try { cssText = matcher.replaceFirst("src: url(" + page.getFullyQualifiedUrl(url) + ");"); } catch (final Exception e) { switch (url) { case "//:": cssText = matcher.replaceFirst("src: url(" + "http:///" + ");"); break; case "//": cssText = matcher.replaceFirst("src: url(" + "http:" + ");"); break; default: } } } else { cssText = StringUtils.replace(cssText, "{", "{\n "); cssText = StringUtils.replace(cssText, "}", ";\n}"); cssText = StringUtils.replace(cssText, "; ", ";\n "); cssText = REPLACEMENT_1.matcher(cssText).replaceFirst("font-family: \"$1\";"); cssText = REPLACEMENT_2.matcher(cssText).replaceFirst("src: url(\"$1\");"); } return cssText; }
From source file:com.ushahidi.chambua.service.EntityExtractorService.java
/** * Extracts named entities from the provided text. The first * step is to determine the content type of the text. * //from w w w. j a va 2s . c o m * @param text * @return com.ushahidi.swiftriver.tagger.dto.APIResponseDTO */ public APIResponseDTO getEntities(String text) { String cleanedContent = null; try { cleanedContent = articleExtractor.getText(text); } catch (BoilerpipeProcessingException e) { LOGGER.error("An error occurred while cleaning the input: {}", e.getMessage()); } String labeledText = classifier.classifyWithInlineXML(cleanedContent); // Entity types/classes available in the classifier e.g. PERSON, LOCATION, ORGANIZATION Set<String> tags = classifier.labels(); String background = classifier.backgroundSymbol(); // Build out the regex string String tagPattern = ""; for (String tag : tags) { if (background.equals(tag)) continue; if (tagPattern.length() > 0) { tagPattern += "|"; } tagPattern += tag; } // Patterns for extracting the labeled text Pattern startPattern = Pattern.compile("<(" + tagPattern + ")>"); Pattern endPattern = Pattern.compile("</(" + tagPattern + ")>"); // Map to store the extracted entities/tags Map<String, Set<String>> entityMap = new HashMap<String, Set<String>>(); // Begin extraction Matcher m = startPattern.matcher(labeledText); while (m.find()) { int start = m.start(); labeledText = m.replaceFirst(""); m = endPattern.matcher(labeledText); if (m.find()) { int end = m.start(); String tag = m.group(1).toLowerCase(); labeledText = m.replaceFirst(""); String entity = labeledText.substring(start, end); if (entityMap.containsKey(tag)) { Set<String> current = entityMap.get(tag); current.add(entity); entityMap.put(tag, current); } else { Set<String> entities = new HashSet<String>(); entities.add(entity); entityMap.put(tag, entities); } } // Adjust the matcher m = startPattern.matcher(labeledText); } DocumentData apiResponse = new DocumentData(); if (entityMap.containsKey("person")) { apiResponse.setPeople(new ArrayList<String>(entityMap.get("person"))); } if (entityMap.containsKey("organization")) { apiResponse.setOrganizations(new ArrayList<String>(entityMap.get("organization"))); } // Geocode the location entities via the Gisgraphy REST API if (entityMap.containsKey("location")) { List<Place> places = new ArrayList<DocumentData.Place>(); try { places = geocodePlaceNames(entityMap.get("location")); apiResponse.setPlaces(places); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return beanMapper.map(apiResponse, APIResponseDTO.class); }
From source file:com.syscrest.oozie.graphite.GraphiteMRCounterExecutor.java
private void apply(Counter counter) throws RuntimeException { for (Map.Entry<String, Long> sourceEntry : counter.getSource().entrySet()) { for (Map.Entry<String, String> mapping : counter.getRules().entrySet()) { Matcher matcher = Pattern.compile(mapping.getKey()).matcher(sourceEntry.getKey()); if (matcher.matches()) { String metricsName = metricsPathPrefix + "." + (mapping.getValue() != null ? matcher.replaceFirst(mapping.getValue()) : sourceEntry.getKey()); // TODO sanitize metric name properly, for now strip out // whitespaces and replace them with underlines metricsName = metricsName.replaceAll("\\s", "_"); if (graphiteData.containsKey(metricsName)) { throw new RuntimeException("duplicate metricsName = \"" + metricsName + "\", aborting"); } else { graphiteData.put(metricsName, sourceEntry.getValue()); }//from w w w. j a v a 2 s .c o m } } } }
From source file:org.phenotips.data.internal.PhenoTipsFeature.java
/** * Constructor that copies the data from an XProperty value. * * @param doc the XDocument representing the described patient in XWiki * @param property the feature category XProperty * @param value the specific value from the property represented by this object *///from w w w .j a v a 2 s.co m public PhenoTipsFeature(XWikiDocument doc, ListProperty property, String value) { super(value); this.propertyName = property.getName(); Matcher nameMatch = NEGATIVE_PREFIX.matcher(this.propertyName); this.present = !nameMatch.lookingAt(); this.type = nameMatch.replaceFirst(""); this.metadata = new TreeMap<>(); String metadataNotes = ""; try { BaseObject metadataObject = findMetadataObject(doc); if (metadataObject != null) { for (FeatureMetadatum.Type metadataType : FeatureMetadatum.Type.values()) { StringProperty metadataProp = (StringProperty) metadataObject.get(metadataType.toString()); if (metadataProp != null && StringUtils.isNotBlank(metadataProp.getValue())) { this.metadata.put(metadataType.toString(), new PhenoTipsFeatureMetadatum(metadataProp)); } } metadataNotes = metadataObject.getLargeStringValue("comments"); } } catch (XWikiException ex) { // Cannot access metadata, simply ignore this.logger.info("Failed to retrieve phenotype metadata: {}", ex.getMessage()); } this.notes = StringUtils.defaultIfBlank(metadataNotes, ""); // Readonly from now on this.metadata = Collections.unmodifiableMap(this.metadata); List<String> categoriesList = Collections.emptyList(); try { BaseObject categoriesObject = findCategoriesObject(doc); if (categoriesObject != null && categoriesObject.getListValue(META_PROPERTY_CATEGORIES) != null) { @SuppressWarnings("unchecked") List<String> originalCategories = categoriesObject.getListValue(META_PROPERTY_CATEGORIES); categoriesList = Collections.unmodifiableList(originalCategories); } } catch (XWikiException ex) { // Cannot access metadata, simply ignore this.logger.info("Failed to retrieve phenotype categories: {}", ex.getMessage()); } this.categories = categoriesList; }
From source file:com.asual.summer.core.faces.FacesResponseWriter.java
private void printTextIfNecessary(boolean end) throws IOException { String textStr = textWriter.toString(); if (StringUtils.hasText(textStr)) { String name = nodeDepth[depth]; textStr = textStr.replaceAll("\t", INDENT); if (ComponentUtils.isStyleOrScript(name)) { textStr = Pattern.compile("^\\s{" + calculateIndent(textStr) + "}", Pattern.MULTILINE) .matcher(textStr).replaceAll(getIndent(depth)).trim(); }//from ww w. ja v a 2s. c om if (block.contains(name) && !pre.contains(name)) { Matcher m = Pattern.compile("^( *\\n)+.*", Pattern.DOTALL).matcher(textStr); if (m.matches()) { textStr = m.replaceFirst("$1") + getIndent(depth) + StringUtils.trimLeadingWhitespace(textStr); } else if (start) { textStr = "\n" + getIndent(depth) + StringUtils.trimLeadingWhitespace(textStr); } m = Pattern.compile(".*(\\n)+ *$", Pattern.DOTALL).matcher(textStr); if (m.matches()) { textStr = StringUtils.trimTrailingWhitespace(textStr) + m.replaceFirst("$1") + getIndent(depth); } } if (end) { textStr = StringUtils.trimTrailingWhitespace(textStr); } writer.write(textStr); textWriter.getBuffer().setLength(0); start = false; nodeDepth[depth + 1] = null; for (int i = 0; i < depth + 1; i++) { nodeDepthContent[i] = true; } } }
From source file:info.magnolia.cms.beans.config.ModuleRegistration.java
/** * Changes the doctype to the correct dtd path (in the classpath) * @param name name of the xml resource// w w w .ja va2 s. com * @return the reader for passing to the beanReader * @throws IOException * @throws JDOMException */ private String getXML(String name) throws IOException, JDOMException { URL dtdUrl = getClass().getResource("/info/magnolia/cms/module/module.dtd"); String content = IOUtils.toString(getClass().getResourceAsStream(name)); // remove doctype Pattern pattern = Pattern.compile("<!DOCTYPE .*>"); Matcher matcher = pattern.matcher(content); content = matcher.replaceFirst(""); // set doctype to the dtd Document doc = new SAXBuilder().build(new StringReader(content)); doc.setDocType(new DocType("module", dtdUrl.toString())); // write the xml to the string XMLOutputter outputter = new XMLOutputter(); StringWriter writer = new StringWriter(); outputter.output(doc, writer); return writer.toString(); }
From source file:net.krautchan.data.KCPosting.java
public String getKcStyledContent() { String kcStyledContent = originalContent.replaceAll("<br>", "\n>"); Matcher kcMatcher = kcLinkPat.matcher(kcStyledContent); while (kcMatcher.find()) { kcStyledContent = kcMatcher.replaceAll(">>" + kcMatcher.group(1)); }/*from w w w . j a v a 2s . c o m*/ Matcher spoilerMatcher = spoilerPat.matcher(kcStyledContent); while (spoilerMatcher.find()) { kcStyledContent = ">>" + spoilerMatcher.replaceAll("[spoiler]" + spoilerMatcher.group(1) + "[/spoiler]"); } Matcher quoteMatcher = quotePat.matcher(kcStyledContent); while (quoteMatcher.find()) { kcStyledContent = quoteMatcher.replaceFirst(quoteMatcher.group(1)); quoteMatcher = quotePat.matcher(kcStyledContent); } kcStyledContent = ">" + kcStyledContent; return kcStyledContent.trim(); }
From source file:com.jajja.arachne.net.Domain.java
public String getDeprefixed() { String registered = getRegistered(); // Don't remove www from "www.com", etc if (registered == null || registered.equalsIgnoreCase(string)) { return string.toLowerCase(); }/*from w ww. ja v a2 s .c o m*/ Matcher m = deprefixHostPattern.matcher(string); return m.replaceFirst(""); }
From source file:com.scm.reader.livescanner.search.Search.java
public String getUrl() { if (url != null) { // needed to maintain compatibility with clients which have taken pictures before // Shortcut 2.0. See Search.getUrl() method Pattern oldUrlPattern = Pattern.compile(OLD_URL_REGEX); Matcher matcher = oldUrlPattern.matcher(url); if (matcher.matches()) { String newUrl = KConfig.getConfig().getServer() + "/app/#/results/$1_$2"; return matcher.replaceFirst(newUrl); } else {/*from www . j a v a2 s. com*/ return url; } } else { return url; } }
From source file:org.apache.hise.utils.RegexpTemplateEngine.java
public String merge(String template, Map<String, Object> presentationParameterValues) { Pattern blockPattern = Pattern.compile("\\?IF\\-[A-Za-z0-9]*\\?.*\\?ENDIF\\-[A-Za-z0-9]*\\?"); Matcher m = blockPattern.matcher(template); //- remove blocks from template if the key is not in presentationParameterValues.keySet or value is null //- remove block markers otherwise while (m.find() == true) { String key = m.group().substring(4).replaceAll("\\?.*$", ""); if (presentationParameterValues.get(key) == null) { template = m.replaceFirst(""); } else {/*from ww w . j a v a 2 s . c o m*/ template = template.replace("?IF-" + key + "?", "").replace("?ENDIF-" + key + "?", ""); } m = blockPattern.matcher(template); } Pattern replacePattern = Pattern.compile("\\$[A-Za-z0-9]*\\$"); m = replacePattern.matcher(template); while (m.find() == true) { String key = m.group().replace("$", ""); Object substitution = ((presentationParameterValues == null) ? null : presentationParameterValues.get(key)); String substitutionString = (substitution == null) ? "error:" + key : substitution.toString(); if (substitutionString == null) { log.warn("Cannot find presentation parameter: " + key); } else { template = m.replaceFirst(substitutionString); m = replacePattern.matcher(template); } } return template; }