Java Code Examples for java.util.regex.Matcher#appendTail()

The following examples show how to use java.util.regex.Matcher#appendTail() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WikiParser.java    From dkpro-jwktl with Apache License 2.0 6 votes vote down vote up
/** Removes texts withing curly brackets, e.g. {{templates}}.<br><br>
 * 
 * Todo: expand templates (optionally).
 */
public static StringBuffer parseCurlyBrackets(StringBuffer text)
{
    if(null == text || 0 == text.length()) {
        return NULL_STRINGBUFFER;
    }
    
    Matcher m = ptrn_double_curly_brackets.matcher(text.toString()); // {{(.+?)}}
    boolean result = m.find();
    if(result) {
        StringBuffer sb = new StringBuffer();
        while(result) {
            //String g = m.group(1); // texts within {{curly brackets}}
            m.appendReplacement(sb, "");
            result = m.find();
        }
        m.appendTail(sb);

        return sb;
    }
    
    return text;
}
 
Example 2
Source File: Markdown.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
public String addHeaderAndFooterStrict(String content, String title) {

        try(InputStream is = MainApp.class.getResourceAsStream("assets/static/html/template-strict-begin.html"))  {
            String template= IOUtils.toString(is, "UTF-8");
            Matcher pathMatcher = Pattern.compile("%%(.*)%%").matcher(template);
            StringBuffer sb = new StringBuffer();
            while (pathMatcher.find()) {
                String path = MainApp.class.getResource("assets" + pathMatcher.group(1)).toExternalForm();
                pathMatcher.appendReplacement(sb, path);
            }
            pathMatcher.appendTail(sb);
            CONTENT_STRICT_BEFORE = new String(sb).replace("##title##", title.toUpperCase());
        } catch (IOException e) {
            log.error("Error when reading the template stream.", e);
        }

        return CONTENT_STRICT_BEFORE+content+CONTENT_STRICT_AFTER;
    }
 
Example 3
Source File: Content.java    From EpubParser with Apache License 2.0 6 votes vote down vote up
private String findAndRemove(String text, String regex) {

		Pattern titleTagPattern = Pattern.compile(regex);
		Matcher titleTagMatcher = titleTagPattern.matcher(text);

		StringBuffer stringBuffer = new StringBuffer();

		while (titleTagMatcher.find()) {
			titleTagMatcher.appendReplacement(stringBuffer, "");
		}

		if (stringBuffer.length() > 0) {
			titleTagMatcher.appendTail(stringBuffer);
			return stringBuffer.toString();
		}

		return text;
	}
 
Example 4
Source File: HtmlEntitiesRepair.java    From markdown-doclet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String afterMarkdownParser(String markup) {
    final StringBuffer result = new StringBuffer();
    final Matcher matcher = RESTORE_REGEX.matcher(markup);
    while (matcher.find()) {
        String replacement = MARKER;
        if (!storage.isEmpty()) {
            replacement = storage.remove(0);
        }

        if (!STORED_MARKER.equals(replacement)) {
            matcher.appendReplacement(result, replacement);
        } else {
            matcher.appendReplacement(result, MARKER);
        }
    }

    matcher.appendTail(result);

    return result.toString();
}
 
Example 5
Source File: Template.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static String expandTemplate(String template, Resolver res) {
    CharSequence in = template;
    StringBuffer out = new StringBuffer();
    while (true) {
        boolean more = false;
        Matcher m = pattern.matcher(in);
        while (m.find()) {
            String major = m.group(1);
            String minor = m.group(2);
            Template key = res.lookup(major);
            if (key == null)
                throw new IllegalStateException("Unknown major key " + major);

            String replacement = key.expand(minor == null ? "" : minor);
            more |= pattern.matcher(replacement).find();
            m.appendReplacement(out, replacement);
        }
        m.appendTail(out);
        if (!more)
            return out.toString();
        else {
            in = out;
            out = new StringBuffer();
        }
    }
}
 
Example 6
Source File: GifMedia.java    From meatspace-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * correct malformed data by:
 * - removing the gif prefix "data:image/gif;base64,"
 * - replacing "%2b" by "+"
 * - replacing "%2f" by "/"
 *
 * @param template string source
 * @return unescaped string
 */
public static String unescape(String template) {
    Map<String,String> tokens = new HashMap<String,String>();
    tokens.put(GIF_PREFIX, "");
    tokens.put("%2b", "+");
    tokens.put("%2f", "/");

    String patternString = "(" + StringUtils.join(tokens.keySet(), "|") + ")";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(template);

    StringBuffer sb = new StringBuffer();
    while(matcher.find()) {
        matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
    }
    matcher.appendTail(sb);

    return sb.toString();
}
 
Example 7
Source File: Text.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Remove tags from the given string, except for &lt;lt&gt; and &lt;gt&gt;
 *
 * @param str The string to remove formatting tags from.
 * @return The given string with all formatting tags removed from it.
 */
public static String removeFormattingTags(String str)
{
	StringBuffer stringBuffer = new StringBuffer();
	Matcher matcher = TAG_REGEXP.matcher(str);
	while (matcher.find())
	{
		matcher.appendReplacement(stringBuffer, "");
		String match = matcher.group(0);
		switch (match)
		{
			case "<lt>":
			case "<gt>":
				stringBuffer.append(match);
				break;
		}
	}
	matcher.appendTail(stringBuffer);
	return stringBuffer.toString();
}
 
Example 8
Source File: AbstractStringReplacer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1 || args.length > 2) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	if (args.length == 2 && !(args[1] instanceof Literal)) {
		throw new ValueExprEvaluationException("Second argument must be a string");
	}
	String s = ((Literal) args[0]).getLabel();
	String regex = (args.length == 2) ? ((Literal) args[1]).getLabel() : ".";
	StringBuffer buf = new StringBuffer(s.length());
	Matcher matcher = Pattern.compile(regex).matcher(s);
	while (matcher.find()) {
		String g = matcher.group();
		matcher.appendReplacement(buf, transform(g));
	}
	matcher.appendTail(buf);
	return valueFactory.createLiteral(buf.toString());
}
 
Example 9
Source File: GenericExternalProcess.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Interpolate parameter values. The replace pattern is {@code ${name}}.
 * @param s a string to search for placeholders
 * @return the resolved string
 * @see #addParameter(java.lang.String, java.lang.String)
 */
static String interpolateParameters(String s, Map<String, String> parameters) {
    if (s == null || s.length() < 4 || parameters.isEmpty()) { // minimal replaceable value ${x}
        return s;
    }
    // finds ${name} patterns
    Matcher m = REPLACE_PARAM_PATTERN.matcher(s);
    StringBuffer sb = null;
    while(m.find()) {
        if (m.groupCount() == 1) {
            String param = m.group(1);
            String replacement = parameters.get(param);
            if (replacement != null) {
                sb = sb != null ? sb : new StringBuffer();
                m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
            }
        }
    }
    if (sb == null) {
        return s;
    }
    m.appendTail(sb);
    return sb.toString();
}
 
Example 10
Source File: TemplateBuilder.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private String parseTextMessage(StreamDefinition streamDefinition, String template) {
    // note: currently we do not support arbitrary data to be mapped with dynamic options
    List<String> attributes = Arrays.asList(streamDefinition.getAttributeNameArray());
    StringBuffer result = new StringBuffer();
    Matcher m = DYNAMIC_PATTERN.matcher(template);
    while (m.find()) {
        if (m.group(1) != null) {
            int attrIndex = attributes.indexOf(m.group(1).replaceAll("\\p{Ps}", "").replaceAll("\\p{Pe}", ""));
            if (attrIndex >= 0) {
                m.appendReplacement(result, String.format("{{%s}}", attrIndex));
            } else {
                throw new NoSuchAttributeException(String.format("Attribute : %s does not exist in %s.",
                        m.group(1), streamDefinition));
            }
        } else {
            m.appendReplacement(result, m.group() + "");
        }
    }
    m.appendTail(result);
    return result.toString();
}
 
Example 11
Source File: CypherUtil.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public String resolveRelationships(String cypher) {
  Matcher m = ENTAILMENT_PATTERN.matcher(cypher);
  StringBuffer buffer = new StringBuffer();
  while (m.find()) {
    String varName = m.group(1);
    String types = m.group(2);
    String modifiers = m.group(3);
    Collection<String> resolvedTypes = resolveTypes(types, modifiers.contains("!"));
    modifiers = modifiers.replaceAll("!", "");
    String typeString = resolvedTypes.isEmpty() ? "" : ":`" + on("`|`").join(resolvedTypes) + "`";
    m.appendReplacement(buffer, "[" + varName + typeString + modifiers + "]");
  }
  m.appendTail(buffer);
  return buffer.toString();
}
 
Example 12
Source File: AbstractCollectionDatasource.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String getJPQLQuery(Map<String, Object> parameterValues) {
    String query;
    if (filter == null)
        query = this.query;
    else
        query = filter.processQuery(this.query, parameterValues);

    for (ParameterInfo info : queryParameters) {
        String paramName = info.getName();
        String jpaParamName = info.getFlatName();

        Pattern p = Pattern.compile(paramName.replace("$", "\\$") + "([^.]|$)"); // not ending with "."
        Matcher m = p.matcher(query);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, jpaParamName + "$1");
        }
        m.appendTail(sb);
        query = sb.toString();

        Object value = parameterValues.get(paramName);
        if (value != null) {
            parameterValues.put(jpaParamName, value);
        }
    }
    query = query.replace(":" + ParametersHelper.CASE_INSENSITIVE_MARKER, ":");

    query = TemplateHelper.processTemplate(query, parameterValues);

    return query;
}
 
Example 13
Source File: HTMLFilter.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
private String escapeComments(final String s)
{
    final Matcher m = P_COMMENTS.matcher(s);
    final StringBuffer buf = new StringBuffer();
    if (m.find())
    {
        final String match = m.group(1); // (.*?)
        m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
    }
    m.appendTail(buf);

    return buf.toString();
}
 
Example 14
Source File: RakeAlgorithm.java    From RAKE-Java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<String> generateCandidateKeywords(List<String> pSentenceList, List<Pattern> pStopWordPattern) {
    List<String> candidates = new ArrayList<>();
    StringBuffer sb = new StringBuffer();
    for (String string : pSentenceList) {
        for (Pattern pat : pStopWordPattern) {
            Matcher matcher = pat.matcher(string.trim());
            while (matcher.find()) {
                matcher.appendReplacement(sb, "|");
            }
            matcher.appendTail(sb);
            if (sb.length() > 0) {

                string = sb.toString();
            }
            sb = new StringBuffer();
        }
        List<String> cands = Arrays.asList(string.split("\\|"));
        for (String string1 : cands) {
            if (string1.trim().length() > 0) {
                String[] p = string1.trim().split("\\s+");
                if (string1.length() > 2 && p.length > 1 && !containsDigit(string1)) {
                    candidates.add(string1.trim());
                }
            }
        }
    }
    return candidates;
}
 
Example 15
Source File: AdamantMarkdownProcessor.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
private String render(InlineRenderer renderer, String s) {
    Matcher matcher = renderer.providePattern().matcher(s);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()){
        StringBuilder itemBuilder = new StringBuilder();
        renderer.renderItem(itemBuilder, matcher);
        matcher.appendReplacement(buffer, itemBuilder.toString());
    }

    matcher.appendTail(buffer);

    return buffer.toString();
}
 
Example 16
Source File: DefaultModuleRegistry.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String toCamelCase(String name) {
    StringBuffer result = new StringBuffer();
    Matcher matcher = Pattern.compile("-([^-])").matcher(name);
    while (matcher.find()) {
        matcher.appendReplacement(result, "");
        result.append(matcher.group(1).toUpperCase());
    }
    matcher.appendTail(result);
    return result.toString();
}
 
Example 17
Source File: NotificationRule.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
public Pattern createSpecificRegex(NotificationManager.ConnectionManager conn) {
    Matcher matcher = CommandAliasManager.mMatchVariablesRegex.matcher(regex);
    StringBuffer buf = new StringBuffer();
    while (matcher.find()) {
        String type = matcher.group(1);
        String replaceWith = "";
        if (type.equals("nick"))
            replaceWith = conn.getConnection().getUserNick();
        matcher.appendReplacement(buf, Matcher.quoteReplacement(Pattern.quote(replaceWith)));
    }
    matcher.appendTail(buf);
    return Pattern.compile(buf.toString(), regexCaseInsensitive ? Pattern.CASE_INSENSITIVE : 0);
}
 
Example 18
Source File: RedPacketMessage.java    From LQRWeChat with MIT License 5 votes vote down vote up
private String getEmotion(String var1) {
    Pattern var2 = Pattern.compile("\\[/u([0-9A-Fa-f]+)\\]");
    Matcher var3 = var2.matcher(var1);
    StringBuffer var4 = new StringBuffer();

    while (var3.find()) {
        int var5 = Integer.parseInt(var3.group(1), 16);
        var3.appendReplacement(var4, String.valueOf(Character.toChars(var5)));
    }

    var3.appendTail(var4);
    return var4.toString();
}
 
Example 19
Source File: Formal.java    From AliceBot with Apache License 2.0 5 votes vote down vote up
public String process(Match match)
{
  String result = super.process(match);
  if (result == null || "".equals(result.trim())) return "";

  /* See the description of java.util.regex.Matcher.appendReplacement() in the Javadocs to understand this code. */    
  Pattern p = Pattern.compile("(^\\s*[a-z]|\\s+[a-z])");
  Matcher m = p.matcher(result);
  StringBuffer buffer = new StringBuffer();
  while (m.find())
    m.appendReplacement(buffer, m.group().toUpperCase());
  m.appendTail(buffer);
  return buffer.toString();
}
 
Example 20
Source File: QuestionParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Adapts QTI form field for Tools to use. Some Tools do not accept HTML, so it gets converted to plain text. Also
    * image placeholders get resolved here.
    */
   public static String processHTMLField(String fieldText, boolean forcePlainText, String contentFolderID,
    String resourcesFolderPath) {
String result = forcePlainText ? WebUtil.removeHTMLtags(fieldText) : fieldText;

if (!StringUtils.isBlank(result)) {
    Matcher imageMatcher = IMAGE_PATTERN.matcher(result);
    StringBuffer resultBuilder = new StringBuffer();

    // find image placeholders
    while (imageMatcher.find()) {
	String imageAttributesStr = imageMatcher.group(1);
	
	List<String> imageAttributes = new ArrayList<>(); 
	Collections.addAll(imageAttributes, imageAttributesStr.split("\\|"));
	String fileName = imageAttributes.get(0);
	imageAttributes.remove(0);
	
	// if it is plain text or something goes wrong, the placeholder simply gets removed
	String replacement = "";
	if (!forcePlainText) {
	    if (resourcesFolderPath == null) {
		log.warn("Image " + fileName + " declaration found but its location is unknown.");
	    } else {
		File sourceFile = new File(resourcesFolderPath, fileName);
		if (sourceFile.canRead()) {
		    // copy the image from exploded IMS zip to secure dir in lams-www
		    File uploadDir = UploadFileUtil.getUploadDir(contentFolderID, "Image");
		    String destinationFileName = UploadFileUtil.getUploadFileName(uploadDir, fileName);
		    File destinationFile = new File(uploadDir, destinationFileName);
		    String uploadWebPath = UploadFileUtil.getUploadWebPath(contentFolderID, "Image") + '/'
			    + fileName;
		    try {
			FileUtils.copyFile(sourceFile, destinationFile);
			replacement = "<img src=\"" + uploadWebPath + "\" " + String.join("", imageAttributes)
				+ " />";
		    } catch (IOException e) {
			log.error("Could not store image " + fileName);
		    }
		} else {
		    log.warn("Image " + fileName + " declaration found but it can not be read.");
		}
	    }
	}
	imageMatcher.appendReplacement(resultBuilder, replacement);
    }
    imageMatcher.appendTail(resultBuilder);
    result = resultBuilder.toString();
}

return StringUtils.isBlank(result) ? null : result;
   }