List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:org.betaconceptframework.astroboa.portal.resource.AbstractContentObjectResource.java
private void addMissingPageNumberInRequestURL(Pattern pageNumberPattern) { Matcher pageNumberMatcher = pageNumberPattern.matcher(resourceRequestURL); if (pageNumberMatcher.find()) { return;//from w ww .j av a 2 s . c o m } Pattern templateAndTypePatternInRequest = Pattern.compile( "(?:/(?:t|template|resourceRepresentationTemplate)/[A-Za-z0-9_\\-]+)?(?:/(?:type|resourceRepresentationType)/(xhtml|rss_2.0|rss_1.0|atom_1.0|pdf|excel))?$"); Matcher templateAndTypeMatcher = templateAndTypePatternInRequest.matcher(resourceRequestURL); String pageNumberAndTemplateAndTypeURL = templateAndTypeMatcher.replaceFirst("/pageNumber/1$0"); resourceRequestURL = pageNumberAndTemplateAndTypeURL; }
From source file:me.Wundero.Ray.utils.TextUtils.java
/** * Replace regular expression in a LiteralText object's content. * /* www. j a va 2s . c o m*/ * Note: this method does NOT check between object nodes. So if there is a * match between the original and one of it's children, it is not parsed. * * @param original * The original text. * @param matcher * The pattern to search for in the content. * @param replacer * The function to call when a match is found in order to supply * a textual replacement. * @param useClickHover * Whether or not to parse click and hover actions as well. */ public static LiteralText replaceRegex(LiteralText original, Pattern matcher, Function<LiteralText, Optional<LiteralText>> replacer, boolean useClickHover) { if (original == null) { return null; } List<Text> children = original.getChildren(); LiteralText.Builder builder = original.toBuilder(); TextFormat f = builder.getFormat(); Optional<ClickAction<?>> cl = builder.getClickAction(); Optional<HoverAction<?>> ho = builder.getHoverAction(); Optional<ShiftClickAction<?>> sc = builder.getShiftClickAction(); builder.removeAll(); String content = builder.getContent(); if (matcher.matcher(content).find()) { Matcher m = matcher.matcher(content); if (m.matches()) { builder = replacer.apply(builder.build()).orElse(LiteralText.of("")).toBuilder(); } else { String[] parts = content.split(matcher.pattern()); if (parts.length == 0) { String c = content; builder = null; while ((m = m.reset(c)).find()) { String g = m.group(); LiteralText t = replacer.apply( (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build()) .orElse(LiteralText.of("")); if (builder == null) { builder = t.toBuilder(); } else { builder.append(t); } c = m.replaceFirst(""); } } else { if (content.startsWith(parts[0])) { List<String> alt = Utils.alternate(parts, allmatches(content, matcher)); LiteralText.Builder ob = builder; builder = (LiteralText.Builder) LiteralText.builder(); List<String> pz = Utils.al(parts, true); for (String s : alt) { if (pz.contains(s)) { LiteralText t = replaceRegex(bf(s, ob).build(), matcher, replacer, useClickHover); builder.append(t); } else { Optional<LiteralText> t = replacer.apply((LiteralText) TextUtils .apply(LiteralText.builder(s).format(f), cl, ho, sc).build()); builder.append(t.orElse(LiteralText.of(""))); } } } else { List<String> alt = Utils.alternate(allmatches(content, matcher), parts); LiteralText.Builder ob = builder; builder = (LiteralText.Builder) LiteralText.builder(); List<String> pz = Utils.al(parts, true); for (String s : alt) { if (pz.contains(s)) { builder.append(replaceRegex(bf(s, ob).build(), matcher, replacer, useClickHover)); } else { Optional<LiteralText> t = replacer.apply((LiteralText) TextUtils .apply(LiteralText.builder(s).format(f), cl, ho, sc).build()); builder.append(t.orElse(LiteralText.of(""))); } } } } } } else { if (builder.getClickAction().isPresent()) { boolean r = builder.getClickAction().get() instanceof ClickAction.RunCommand; String click = replaceRegexAction(builder.getClickAction().get(), (s) -> { if (!matcher.matcher(s).find()) { return s; } String out = matcher.matcher(s).replaceAll("%s"); String st = s; Matcher m = matcher.matcher(s); List<Object> b = Utils.al(); while ((m = m.reset(st)).find()) { String g = m.group(); b.add(replacer.apply( (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build()) .orElse(LiteralText.builder("").build()).toPlain()); st = m.replaceFirst(""); } out = format(out, b); return out; }, ""); if (!click.isEmpty()) { if (r) { builder.onClick(TextActions.runCommand(click)); } else { builder.onClick(TextActions.suggestCommand(click)); } } } if (builder.getHoverAction().isPresent()) { Text hover = replaceRegexAction(builder.getHoverAction().get(), (s) -> { String a = TextSerializers.FORMATTING_CODE.serialize(s); if (!matcher.matcher(a).find()) { return s; } String out = matcher.matcher(a).replaceAll("%s"); String st = a; Matcher m = matcher.matcher(a); List<Object> b = Utils.al(); while ((m = m.reset(st)).find()) { String g = m.group(); b.add(TextSerializers.FORMATTING_CODE.serialize(replacer.apply( (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build()) .orElse(LiteralText.builder("").build()))); st = m.replaceFirst(""); } out = format(out, b); return TextSerializers.FORMATTING_CODE.deserialize(out); }, Text.of()); if (!hover.isEmpty()) { builder.onHover(TextActions.showText(hover)); } } } builder.append(children.stream().filter(t -> lit(t)) .map(child -> replaceRegex((LiteralText) child, matcher, replacer, useClickHover)) .collect(RayCollectors.rayList())); return builder.build(); }
From source file:org.betaconceptframework.astroboa.portal.resource.AbstractContentObjectResource.java
protected void generatePageScrollingURLs() throws Exception { int scrollerStartPage; int scrollerEndPage; int pagesToPreceedeOrFollow = (PortalIntegerConstants.MAX_PAGES_IN_PAGE_SCROLLER - 1) / 2; int pagesToPreceed; int pagesToFollow; if ((PortalIntegerConstants.MAX_PAGES_IN_PAGE_SCROLLER - 1) % 2 == 0) { pagesToPreceed = pagesToFollow = pagesToPreceedeOrFollow; } else {//from w w w. j a v a2s .c o m pagesToPreceed = pagesToPreceedeOrFollow; pagesToFollow = pagesToPreceedeOrFollow + 1; } scrollerStartPage = pageNumber - pagesToPreceed; if (scrollerStartPage < 1) { scrollerStartPage = 1; } scrollerEndPage = pageNumber + pagesToFollow; if (scrollerEndPage < PortalIntegerConstants.MAX_PAGES_IN_PAGE_SCROLLER) { scrollerEndPage = PortalIntegerConstants.MAX_PAGES_IN_PAGE_SCROLLER; } if (scrollerEndPage > resourceResponse.getResourceContext().getTotalPages()) { scrollerEndPage = resourceResponse.getResourceContext().getTotalPages(); } Pattern pageNumberPatternInRequestURL = Pattern.compile("pageNumber/[0-9]+"); // if page number is missing from URL we should add it before we proceed to generate the scrolling page URLs addMissingPageNumberInRequestURL(pageNumberPatternInRequestURL); // if text is contained in the request url we should encode it if (StringUtils.isNotBlank(textSearched)) { Pattern textSearchedPatternInRequestURL = Pattern.compile("textSearched/.*?/"); Matcher textSearchedMatcher = textSearchedPatternInRequestURL.matcher(resourceRequestURL); try { String encodedTextSearched = URLEncoder.encode(textSearched, "utf-8"); resourceRequestURL = textSearchedMatcher.replaceFirst("textSearched/" + encodedTextSearched + "/"); } catch (Exception e) { logger.error("A problem occured while encoding the searched text", e); throw e; } } Matcher pageNumberMatcher = pageNumberPatternInRequestURL.matcher(resourceRequestURL); for (int i = scrollerStartPage; i <= scrollerEndPage; ++i) { String scrollerURL = pageNumberMatcher.replaceFirst("pageNumber/" + i); PagedResourceURL pagedResourceURL = new PagedResourceURL(); pagedResourceURL.setPageNumber(i); pagedResourceURL.setURL(scrollerURL); resourceResponse.getResourceContext().getPageScrollingURLs().add(pagedResourceURL); } resourceResponse.getResourceContext().setFirstPageURL(pageNumberMatcher.replaceFirst("pageNumber/" + 1)); resourceResponse.getResourceContext().setLastPageURL(pageNumberMatcher .replaceFirst("pageNumber/" + resourceResponse.getResourceContext().getTotalPages())); }
From source file:de.pksoftware.springstrap.cms.service.CmsService.java
public String convertBase64Images(String modelName, String path, String value) { Pattern base64ImagePattern = Pattern.compile( "\\<img.+src\\=\\\"data\\:(image\\/[a-z]+)\\;base64\\,([a-zA-Z0-9\\+\\/]+[\\=]*)\\\"[^\\>]*\\>"); Pattern fileNamePattern = Pattern.compile("data\\-filename\\=\\\"([\\w\\.\\-\\(\\)]+)\\\""); Matcher base64ImageMatcher = base64ImagePattern.matcher(value); if (base64ImageMatcher.find()) { String imgTag = base64ImageMatcher.group(0); logger.info("Found img tag: {}", imgTag); String mimeType = base64ImageMatcher.group(1); String base64Image = base64ImageMatcher.group(2); logger.info("Found {} Image: {}", mimeType, base64Image); Matcher fileNameMatcher = fileNamePattern.matcher(imgTag); String fileName = null;//from www.java 2 s.c o m if (fileNameMatcher.find()) { fileName = fileNameMatcher.group(1); logger.info("Filename is: {}", fileName); } if (null == fileName) { String fileExtension = getFileExtensionFromMime(mimeType); UUID fileNameUUID = UUID.randomUUID(); fileName = fileNameUUID.toString() + "." + fileExtension; } logger.info("File name is: {}", fileName); String imagePath = "models/" + modelName + "/" + fileName; String finalImagePath = imagePath; /* boolean fileExists = true; int i = 0; while(fileExists){ if(i > 0){ logger.info("File already exists: {}", finalImagePath); finalImagePath = "(" + i + ")" + imagePath; } try { fileExists = fileSystemService.existPublicFile(BUCKET_NAME, finalImagePath); i++; } catch (InvalidPathException | InvalidBucketException e) { break; } } */ byte[] data = Base64.decodeBase64(base64Image); try { SitePath imageSitePath = new SitePath(finalImagePath); fileSystemService.writeFile(ItemVisibility.PUBLIC, cmsBucket, imageSitePath, data, true, true); value = base64ImageMatcher.replaceFirst("<img src=\"" + fileSystemService.getItemURL(ItemVisibility.PUBLIC, cmsBucket, imageSitePath) + "\" />"); } catch (Exception ex) { logger.error("Could not write file: " + ex.getMessage()); } } return value; }
From source file:org.jahia.services.search.facets.SimpleJahiaJcrFacets.java
private NamedList<Object> resolvePropertiesWithNameValues(NamedList<Object> values, String fieldName) { NamedList<Object> resolvedValues = new NamedList<>(); for (Map.Entry<String, Object> facetValueEntry : values) { String facetValueKey = facetValueEntry.getKey(); Matcher matcher = nameFieldPrefix.matcher(facetValueKey); if (matcher.matches()) { String nsPrefix = matcher.group(1); try { nsPrefix = session.getNamespacePrefix(nsMappings.getURI(nsPrefix)); } catch (RepositoryException e) { // use the unconverted prefix }//from ww w . j a va 2s. c o m StringBuilder facetValueBuilder = new StringBuilder(); facetValueBuilder.append(nsPrefix); if (facetValueBuilder.length() > 0) { facetValueBuilder.append(":"); } facetValueBuilder.append("$2"); facetValueKey = matcher.replaceFirst(facetValueBuilder.toString()); if (!FieldNames.PROPERTIES.equals(fieldName)) { facetValueKey = facetValueKey + "##q->##" + facetValueEntry.getKey(); } } resolvedValues.add(facetValueKey, facetValueEntry.getValue()); } return resolvedValues; }
From source file:com.ichi2.anki.AbstractFlashcardViewer.java
/** * Format question field when it contains typeAnswer or clozes. If there was an error during type text extraction, a * warning is displayed/*w w w . j a va 2 s . com*/ * * @param buf The question text * @return The formatted question text */ private String typeAnsQuestionFilter(String buf) { Matcher m = sTypeAnsPat.matcher(buf); if (mTypeWarning != null) { return m.replaceFirst(mTypeWarning); } StringBuilder sb = new StringBuilder(); if (mUseInputTag) { // These functions are definde in the JavaScript file assets/scripts/card.js. We get the text back in // shouldOverrideUrlLoading() in createWebView() in this file. sb.append("<center>\n<input type=text name=typed id=typeans onfocus=\"taFocus();\" " + "onblur=\"taBlur(this);\" onKeyPress=\"return taKey(this, event)\" autocomplete=\"off\" "); // We have to watch out. For the preview we dont know the font or font size. Skip those there. (Anki // desktop just doesnt show the input tag there. Do it with standard values here instead.) if (mTypeFont != null && !TextUtils.isEmpty(mTypeFont) && mTypeSize > 0) { sb.append("style=\"font-family: '" + mTypeFont + "'; font-size: " + Integer.toString(mTypeSize) + "px;\" "); } sb.append(">\n</center>\n"); } else { sb.append("<span id=typeans class=\"typePrompt"); if (!mShowTypeAnswerField) { sb.append(" typeOff"); } sb.append("\">........</span>"); } return m.replaceAll(sb.toString()); }
From source file:com.amalto.workbench.utils.Util.java
public static String formatErrorMessage(String sourceMessage) { String saxExceptionPattern = "\\[\\w*\\]\\s:\\d+:\\d+:\\s.+:\\s"; //$NON-NLS-1$ String nestedExceptionPattern = ";?\\s?nested exception is:[\\w\\W]*"; //$NON-NLS-1$ Pattern pattern = Pattern.compile(saxExceptionPattern); Matcher matcher = pattern.matcher(sourceMessage); String result = matcher.replaceFirst(""); //$NON-NLS-1$ pattern = Pattern.compile(nestedExceptionPattern); matcher = pattern.matcher(result);//from ww w.j a v a 2 s . c o m result = matcher.replaceFirst(""); //$NON-NLS-1$ return result; }
From source file:com.hichinaschool.flashcards.anki.Reviewer.java
/** * Format answer field when it contains typeAnswer or clozes * @param buf The answer text// ww w. j a va 2 s . com * @return The formatted answer text */ private String typeAnsAnswerFilter(String buf) { Matcher m = sTypeAnsPat.matcher(buf); return m.replaceFirst(""); }