Example usage for java.util.regex Matcher appendReplacement

List of usage examples for java.util.regex Matcher appendReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher appendReplacement.

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    CharSequence inputStr = "ab12 cd efg34 123";
    String patternStr = "([a-zA-Z]+[0-9]+)";

    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);

    StringBuffer buf = new StringBuffer();
    boolean found = false;
    while ((found = matcher.find())) {
        String replaceStr = matcher.group();
        matcher.appendReplacement(buf, "found<" + replaceStr + ">");
    }//from  w  w  w.j a v  a 2 s. c o m
    matcher.appendTail(buf);

    String result = buf.toString();
    System.out.println(result);
}

From source file:ReplaceDemo.java

public static void main(String[] argv) {

    // Make an RE pattern to match almost any form (deamon, demon, etc.).
    String patt = "d[ae]{1,2}mon"; // i.e., 1 or 2 'a' or 'e' any combo

    // A test input.
    String input = "Unix hath demons and deamons in it!";
    System.out.println("Input: " + input);

    // Run it from a RE instance and see that it works
    Pattern r = Pattern.compile(patt);
    Matcher m = r.matcher(input);
    System.out.println("ReplaceAll: " + m.replaceAll("daemon"));

    // Show the appendReplacement method
    m.reset();//w  w w.  j a v  a2  s  . c o m
    StringBuffer sb = new StringBuffer();
    System.out.print("Append methods: ");
    while (m.find()) {
        m.appendReplacement(sb, "daemon"); // Copy to before first match,
        // plus the word "daemon"
    }
    m.appendTail(sb); // copy remainder
    System.out.println(sb.toString());
}

From source file:org.eclipse.mylyn.docs.examples.GenerateEPUB.java

public static void main(String[] args) {

    // clean up from last run
    try {/*from  w  w w  . j a  v a 2  s.c o m*/
        Files.delete(Paths.get("loremipsum.html"));
        Files.delete(Paths.get("loremipsum.epub"));
    } catch (IOException e1) {
        /* no worries */ }

    try ( // read MarkDown
            FileReader fr = new FileReader("loremipsum.md");
            // and output HTML
            Writer fw = Files.newBufferedWriter(Paths.get("loremipsum.html"), StandardOpenOption.CREATE)) {

        // generate HTML from markdown
        MarkupParser parser = new MarkupParser();
        parser.setMarkupLanguage(new MarkdownLanguage());
        HtmlDocumentBuilder builder = new HtmlDocumentBuilder(fw);
        parser.setBuilder(builder);
        parser.parse(fr, true);

        // convert any inline equations in the HTML into MathML
        String html = new String(Files.readAllBytes(Paths.get("loremipsum.html")));
        StringBuffer sb = new StringBuffer();
        Matcher m = EQUATION.matcher(html);

        // for each equation
        while (m.find()) {
            // replace the LaTeX code with MathML
            m.appendReplacement(sb, laTeX2MathMl(m.group()));
        }
        m.appendTail(sb);

        // EPUB 2.0 can only handle embedded SVG so we find all referenced
        // SVG files and replace the reference with the actual SVG code
        Document parse = Jsoup.parse(sb.toString(), "UTF-8", Parser.xmlParser());

        Elements select = parse.select("img");
        for (Element element : select) {
            String attr = element.attr("src");
            if (attr.endsWith(".svg")) {
                byte[] svg = Files.readAllBytes(Paths.get(attr));
                element.html(new String(svg));
            }
        }

        // write back the modified HTML-file
        Files.write(Paths.get("loremipsum.html"), sb.toString().getBytes(), StandardOpenOption.WRITE);

        // instantiate a new EPUB version 2 publication
        Publication pub = Publication.getVersion2Instance();

        // include referenced resources (default is false)
        pub.setIncludeReferencedResources(true);

        // title and subject is required
        pub.addTitle("EclipseCon Demo");
        pub.addSubject("EclipseCon Demo");

        // generate table of contents (default is true)
        pub.setGenerateToc(true);
        epub.add(pub);

        // add one chapter
        pub.addItem(Paths.get("loremipsum.html").toFile());

        // create the EPUB
        epub.pack(new File("loremipsum.epub"));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:Main.java

public static void main(String[] args) {
    String regex = "\\b\\d+\\b";
    StringBuffer sb = new StringBuffer();
    String replacementText = "";
    String matchedText = "";

    String text = "We have 7 tutorials for Java, 2 tutorials for Javascript and 1 tutorial for Oracle.";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);

    while (m.find()) {
        matchedText = m.group();/*from w w  w  .  ja  v  a 2  s  .c o  m*/
        int num = Integer.parseInt(matchedText);
        if (num == 1) {
            replacementText = "only one";
        } else if (num < 5) {
            replacementText = "a few";
        } else {
            replacementText = "many";
        }
        m.appendReplacement(sb, replacementText);
    }

    m.appendTail(sb);
    System.out.println("Old  Text: " + text);
    System.out.println("New Text: " + sb.toString());
}

From source file:Main.java

public static String html2Text(String html) {
    StringBuffer filterText = new StringBuffer();

    Pattern p = Pattern.compile("<([^>]*)>");
    Matcher m = p.matcher(html);
    while (m.find()) {
        m.appendReplacement(filterText, "");
    }// w ww  .j  ava  2s  .c  o m
    m.appendTail(filterText);

    return unescapeHTML(filterText.toString());
}

From source file:Main.java

private static String urlEncode(String str, String charset) throws UnsupportedEncodingException {
    Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
    Matcher m = p.matcher(str);
    StringBuffer b = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
    }/*  ww  w  .  ja va2 s.c o m*/
    m.appendTail(b);
    return b.toString();
}

From source file:Main.java

public static StringBuffer removePatternContents(String defStr, Pattern pat) {
    Matcher mat = pat.matcher(defStr);
    StringBuffer sb = new StringBuffer();
    while (mat.find()) {
        mat.appendReplacement(sb, " ");
    }/*  w  w w .  j  a v  a 2s  .  co m*/
    mat.appendTail(sb);
    return sb;
}

From source file:Main.java

public static String getClassNameFromTableName(String tableName) {
    Pattern p = Pattern.compile("(_+|^)(\\w?)");
    Matcher m = p.matcher(tableName);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group(2).toUpperCase());
    }/*w ww  .  j a v  a 2 s.c o  m*/
    m.appendTail(sb);

    return sb.toString();
}

From source file:Main.java

/**
 * Remove xml comments from the xml string.
 * // w  w w .  j av a  2  s . co m
 * @param xml
 * @return
 */
public static String stripXMLComment(CharSequence xml) {
    if (xml == null) {
        return null;
    }

    // option DOTALL: '.' matches newlines
    // use '.+?' in stead of '.*': non-greedy matching ("<!-- --> <important-stuff\> <!-- -->" is replaced with " <important-stuff\> ")
    Pattern p = Pattern.compile("<!--.+?-->", Pattern.DOTALL); //$NON-NLS-1$
    Matcher m = p.matcher(xml);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, ""); //$NON-NLS-1$
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.titankingdoms.dev.titanchat.format.Censor.java

/**
 * Filters the text for phrases and censors the phrases with the censor
 * //from   w  ww.j  a  va2s  . c o m
 * @param text The text to filter
 * 
 * @param phrases The phrases to censor
 * 
 * @param censor The censor to use
 * 
 * @return The filtered text
 */
public static String filter(String text, List<String> phrases, String censor) {
    if (text == null)
        return "";

    if (phrases == null)
        return text;

    if (censor == null)
        censor = "";

    StringBuffer filtered = new StringBuffer();

    String regex = "(" + StringUtils.join(phrases.toArray(new String[0])) + ")";

    Pattern phrasePattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher match = phrasePattern.matcher(text);

    while (match.find())
        match.appendReplacement(filtered, Pattern.compile(".").matcher(match.group()).replaceAll(censor));

    return match.appendTail(filtered).toString();
}