Java Regex String Replace Whitespace replaceWhitespaces(String inString, String with)

Here you can find the source of replaceWhitespaces(String inString, String with)

Description

replace Whitespaces

License

Open Source License

Declaration

public static String replaceWhitespaces(String inString, String with) 

Method Source Code

//package com.java2s;
/**//from   w w  w . j ava  2  s.c o m
 * DataCleaner (community edition)
 * Copyright (C) 2014 Neopost - Customer Information Management
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */

import java.util.regex.Pattern;

public class Main {
    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("[\\s\\p{Zs}\\p{javaWhitespace}]+");

    public static String replaceWhitespaces(String inString, String with) {
        return WHITESPACE_PATTERN.matcher(inString).replaceAll(with);
    }

    /**
     * Utility method that will do replacement multiple times until no more
     * occurrences are left.
     * 
     * Note that this is NOT the same as
     * {@link String#replaceAll(String, String)} which will only do one
     * run-through of the string, and it will use regexes instead of exact
     * searching.
     * 
     * @param v
     * @param searchToken
     * @param replacement
     * @return
     */
    public static String replaceAll(String v, String searchToken, String replacement) {
        if (v == null) {
            return v;
        }
        while (v.indexOf(searchToken) != -1) {
            v = v.replace(searchToken, replacement);
        }
        return v;
    }

    public static int indexOf(final char c, final char[] chars) {
        for (int i = 0; i < chars.length; i++) {
            if (c == chars[i]) {
                return i;
            }
        }
        return -1;
    }
}

Related

  1. replaceBlank(String str)
  2. replaceWhitespace(final String value, final boolean stripExtras)
  3. replaceWhitespace(final String value, final boolean stripExtras)
  4. replaceWhitespace(String searchTerm)
  5. replaceWhiteSpaces(final String value, final String replaceBy)
  6. replaceWhitespaces(String inString, String with)
  7. replaceWhiteSpaces(String str)
  8. replaceWhiteSpacesByMinusSign(final String value)