简体   繁体   中英

Java 1.3 String.replaceAll() , replacement

I'm working with some really old Java. 1.3 Java. 1.3 to be exact.

I'm attempting to sanitize some String input by removing non alphabet characters (punctuation and numbers, etc)

Normally I'd do something like:

String.replaceAll("[^A-Za-z]", "");

However, .replaceAll() was introduced in Java 1.4 ! So it won't compile! http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)

How did we accomplish this prior to Java 1.4 ?

Well probably you can write a simple loop like this:

char[] origArr = str.toCharArray();
char[] destArr = new char[origArr.length];
int j = 0;
for (int i=0; i < origArr.length; i++) {
    char c = origArr[i];
    if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
       destArr[j++] = c;
}

String dest = new String(destArr, 0, j);

Sorry don't have JDK1.3 to test it out.

See if this works:

public static String replaceAll(
    String haystack,              // String to search in
    String needle,                // Substring to find
    String replacement) {         // Substring to replace with

    int i = haystack.lastIndexOf( needle );
    if ( i != -1 ) {
        StringBuffer buffer = new StringBuffer( haystack );
        buffer.replace( i, i+needle.length(), replacement );
        while( (i=haystack.lastIndexOf(needle, i-1)) != -1 ) {
            buffer.replace( i, i+needle.length(), replacement );
        }
        haystack = buffer.toString();
    }

    return haystack;
}

EDIT: This won't support regular expressions. As you're looking to erase more than just a single character, I would suggest you either tweak this code to allow an array of needles or (the ugly method) loop through the disallowed characters and repeatedly call the function.

You can use jakarta by the Apache Software Foundation.

Jakarta Regexp is a 100% Pure Java Regular Expression package

It's not maintained but the last version is not so old (2011).

The documentation: http://jakarta.apache.org/regexp/

For the replaceAll you can use subst with the REPLACE_ALL flag.

PS: The link is dead, here a mirror to download the lib .

Assuming you need only alphabets and anything else to be replaced with blank. Character also got isDigit method. please refer to http://docs.oracle.com/javase/1.3/docs/api/java/lang/Character.html if it helps.

public static void main (String[] args)
{


String yourstring = "2323ABF!@CD24";
char[] check = yourstring.toCharArray();
StringBuffer str = new StringBuffer();
for(int i=0; i < check.length; i++){
    if(!Character.isLetter(check[i])){
       str.append("");
    }
    else{
        str.append(check[i]);
    }
}
System.out.println(str.toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM