Example usage for java.util.regex Matcher replaceAll

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

Introduction

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

Prototype

public String replaceAll(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces every subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:org.alfresco.selenium.FetchUtil.java

/**
 * Checks and removes meta tags such as:
 * <meta href= /> as it was causing some conflicts with images url
 * that shared the same path./*from w  w  w  .  jav a2s. co m*/
 * 
 * @param value HTML source
 * @return 
 */
public static String stripMetaTag(String value) {
    if (null == value) {
        throw new IllegalArgumentException("input required");
    }
    //Extract all source files
    Matcher matchSrc = META_TAG.matcher(value);
    return matchSrc.replaceAll("");
}

From source file:com.wxxr.nirvana.json.TestUtils.java

/**
 * normalizes a string so that strings generated on different platforms can
 * be compared. any group of one or more space, tab, \r, and \n characters
 * are converted to a single space character
 * /*from  ww w . j a  v a 2 s. c om*/
 * @param obj
 *            the object to be normalized. normalize will perform its
 *            operation on obj.toString().trim() ;
 * @param appendSpace
 * @return the normalized string
 */
public static String normalize(Object obj, boolean appendSpace) {
    Matcher matcher = WHITESPACE_BLOCK.matcher(StringUtils.trim(obj.toString()));
    /*
    FIXME: appendSpace has been always ignored, uncommenting the following line will cause dozen of test fails
    if (appendSpace) {
    return matcher.replaceAll(" ");
    }
    */
    return matcher.replaceAll("");
}

From source file:org.datavec.api.records.writer.impl.SVMLightRecordWriterTest.java

public static void executeTest(Configuration configWriter, Configuration configReader, File inputFile)
        throws Exception {
    File tempFile = File.createTempFile("SVMLightRecordWriter", ".txt");
    tempFile.setWritable(true);/*  w  ww.  j a  va 2s .  c  om*/
    tempFile.deleteOnExit();
    if (tempFile.exists())
        tempFile.delete();

    try (SVMLightRecordWriter writer = new SVMLightRecordWriter()) {
        FileSplit outputSplit = new FileSplit(tempFile);
        writer.initialize(configWriter, outputSplit, new NumberOfRecordsPartitioner());
        SVMLightRecordReader rr = new SVMLightRecordReader();
        rr.initialize(configReader, new FileSplit(inputFile));
        while (rr.hasNext()) {
            List<Writable> record = rr.next();
            writer.write(record);
        }
    }

    Pattern p = Pattern.compile(String.format("%s:\\d+ ", SVMLightRecordReader.QID_PREFIX));
    List<String> linesOriginal = new ArrayList<>();
    for (String line : FileUtils.readLines(inputFile)) {
        if (!line.startsWith(SVMLightRecordReader.COMMENT_CHAR)) {
            String lineClean = line.split(SVMLightRecordReader.COMMENT_CHAR, 2)[0];
            if (lineClean.startsWith(" ")) {
                lineClean = " " + lineClean.trim();
            } else {
                lineClean = lineClean.trim();
            }
            Matcher m = p.matcher(lineClean);
            lineClean = m.replaceAll("");
            linesOriginal.add(lineClean);
        }
    }
    List<String> linesNew = FileUtils.readLines(tempFile);
    assertEquals(linesOriginal, linesNew);
}

From source file:net.sourceforge.fenixedu.util.StringFormatter.java

protected static String removeDuplicateSpaces(String string) {
    Pattern pattern = Pattern.compile("\\s+");
    Matcher matcher = pattern.matcher(string);
    return matcher.replaceAll(" ");
}

From source file:org.datavec.api.records.writer.impl.LibSvmRecordWriterTest.java

public static void executeTest(Configuration configWriter, Configuration configReader, File inputFile)
        throws Exception {
    File tempFile = File.createTempFile("LibSvmRecordWriter", ".txt");
    tempFile.setWritable(true);/*from   w w w.  j  a  v  a  2 s .com*/
    tempFile.deleteOnExit();
    if (tempFile.exists())
        tempFile.delete();

    try (LibSvmRecordWriter writer = new LibSvmRecordWriter()) {
        FileSplit outputSplit = new FileSplit(tempFile);
        writer.initialize(configWriter, outputSplit, new NumberOfRecordsPartitioner());
        LibSvmRecordReader rr = new LibSvmRecordReader();
        rr.initialize(configReader, new FileSplit(inputFile));
        while (rr.hasNext()) {
            List<Writable> record = rr.next();
            writer.write(record);
        }
    }

    Pattern p = Pattern.compile(String.format("%s:\\d+ ", LibSvmRecordReader.QID_PREFIX));
    List<String> linesOriginal = new ArrayList<>();
    for (String line : FileUtils.readLines(inputFile)) {
        if (!line.startsWith(LibSvmRecordReader.COMMENT_CHAR)) {
            String lineClean = line.split(LibSvmRecordReader.COMMENT_CHAR, 2)[0];
            if (lineClean.startsWith(" ")) {
                lineClean = " " + lineClean.trim();
            } else {
                lineClean = lineClean.trim();
            }
            Matcher m = p.matcher(lineClean);
            lineClean = m.replaceAll("");
            linesOriginal.add(lineClean);
        }
    }
    List<String> linesNew = FileUtils.readLines(tempFile);
    assertEquals(linesOriginal, linesNew);
}

From source file:com.reizes.shiva.utils.AddrUtil.java

/**
 * addr2? ?   ? ./*from w  w w  .j  a  v  a 2 s  .c o m*/
 * @param addr2
 * @return
 */
public static String getAddr3FromAddr2(String addr2) {
    if (addr2 != null) {
        Matcher matcher2 = PATTERN_ADDR2_2.matcher(addr2);
        if (matcher2.find()) {
            return StringUtil.normalize(StringUtils.strip(matcher2.replaceAll(""), " ,/.\t-_"));
        } else {
            Matcher matcher = PATTERN_ADDR2_1.matcher(addr2);
            if (matcher.find()) {
                return StringUtil.normalize(StringUtils.strip(matcher.replaceAll(""), " ,/.\t-_"));
            }
            return StringUtil.normalize(addr2);
        }
    }

    return null;
}

From source file:com.dmsl.anyplace.nav.AnyPlaceSeachingHelper.java

public static Cursor prepareSearchViewCursor(List<? extends IPoisClass> places, String query) {
    String req_columns[] = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA };
    MatrixCursor mcursor = new MatrixCursor(req_columns);
    int i = 0;/*from   w  w w  .  j a  va 2s.  c om*/
    if (places != null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(IPoisClass.class, new IPoisClass.MyInterfaceAdapter());
        Gson gson = gsonBuilder.create();

        // Better Use AndroidUtils.fillTextBox instead of regular expression
        // Regular expression
        // ?i ignore case
        Pattern patternTitle = Pattern.compile(String.format("((?i)%s)", query));
        // Matches X words before query and Y words after
        Pattern patternDescription = Pattern.compile(
                String.format("(([^\\s]+\\s+){0,%d}[^\\s]*)((?i)%s)([^\\s]*(\\s+[^\\s]+){0,%d})", 2, query, 2));
        for (IPoisClass p : places) {
            String name = "", description = "";
            Matcher m;
            m = patternTitle.matcher(p.name());
            // Makes matched query bold using HTML format
            // $1 returns the regular's expression outer parenthesis value
            name = m.replaceAll("<b>$1</b>");

            m = patternDescription.matcher(p.description());
            if (m.find()) {
                // Makes matched query bold using HTML format
                description = String.format(" %s<b>%s</b>%s", m.group(1), m.group(3), m.group(4));
            }

            mcursor.addRow(new String[] { Integer.toString(i++), name + description,
                    gson.toJson(p, IPoisClass.class) });
        }
    }
    return mcursor;
}

From source file:com.mindquarry.desktop.I18N.java

protected static String getTranslation(String key, Map<String, String> translationMap, String... args) {
    String translation = translationMap.get(key);
    if (translation == null) {
        // quotes are as >>\"<< in the map, but as >>"<< in the key:
        key = key.replaceAll("\"", "\\\\\"");
        // line breaks are entered as "\n" (literally) but we get them as a line
        // break from the parser:
        translation = translationMap.get(key.replace("\n", "\\n"));
        if (translation == null) {
            if (!"en".equals(Locale.getDefault().getLanguage())) {
                // don't log if GUI is English
                log.warn("No translation found for '" + key + "'");
            }//w  w w  .j ava 2 s  . co m
            translation = key;
        }
        translation = translation.replace("\\n", "\n");
        translation = translation.replace("\\\"", "\"");
    }
    int i = 0;
    // "{n}" can be used as a placeholder in the message, it refers
    // to the n-th argument (n starts at 0):
    while (true) {
        Pattern p = Pattern.compile("\\{" + i + "\\}");
        Matcher m = p.matcher(translation);
        if (!m.find()) {
            break;
        }
        try {
            // need to escape backslashes and dollar signs, so that they
            // survive the replaceAll
            translation = m.replaceAll(args[i].replace("\\", "\\\\").replace("$", "\\$"));
        } catch (ArrayIndexOutOfBoundsException e) {
            // happens if the translation contains a "{n}" but there's
            // no parameter for it - fall back to non-translated text:
            log.error("Missing parameter " + i + " for key '" + key + "'");
            return key;
        }
        i++;
    }
    return translation;
}

From source file:edu.temple.cis3238.wiki.utils.StringUtils.java

/**
 * Removes:/*from   w w  w. jav a2 s.c  o m*/
 * <ol>
 * <li>[[[ and ]]]</li>
 * <li>&quot; and apostrophe</li>
 * <li>&amp; ampersand and gt / lt signs &gt; + &lt;</li>
 * <li>semicolon</li>
 * </ol>
 *
 * @param in
 * @return
 */
public static String stripInvalidChars(String in) {
    Pattern pattern = Pattern.compile("(\\[\\[\\[|\\]\\]\\]|\"|'|&|<|>|;)");
    Matcher matcher = pattern.matcher(StringUtils.toS(in));
    try {
        in = matcher.replaceAll("");
    } catch (Exception e) {
    }
    return StringUtils.toS(in);
}

From source file:edu.temple.cis3238.wiki.utils.StringUtils.java

/**
 * Removes all html tags from string// w  w  w .  ja v  a2 s.com
 *
 * @param val
 * @return
 */
public static String removeHtmlMarkups(String val) {
    String clean = "";
    try {
        Pattern pattern = Pattern.compile(REGEX_HTML_MARKUP_CHARS,
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher matcher = pattern.matcher(val);
        try {
            clean = matcher.replaceAll("");
        } catch (IllegalArgumentException ex) {
        } catch (IndexOutOfBoundsException ex) {
        }
    } catch (PatternSyntaxException ex) {
    } //
    return toS(clean);
}