Link to home
Start Free TrialLog in
Avatar of galaxy573
galaxy573

asked on

Java 1.3 JSP replace string w/reg exp.

I need to come up with a good way to search through a string and replaceAll certain characters with another string.

If the string contains either of the following: & ' "
I need to replace all & with "and" and replace all single/double quote with "quote".

In my code below, how do I modify it so it searches for either of the 3 characters, without looping 3 times, one for each char.
String source = "mel & laura & cindy's car";
String input = "";
String pattern = "&";
 
if (source!=null)
{
        final int len = pattern.length();
        StringBuffer sb = new StringBuffer();
        int found = -1;
        int start = 0;
 
        while( (found = source.indexOf(pattern, start) ) != -1) {
            sb.append(source.substring(start, found));
            sb.append(replace);
            start = found + len;
        }
 
        sb.append(source.substring(start));
 
        input =  sb.toString();
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

easier to use replaceAll(), why not use that

Avatar of galaxy573
galaxy573

ASKER

Java 1.3 does not have replaceAll() unfortunately.
sorry didn't notice you were using 1.3.

why is looping a problem? You're already looping (for each instance of the string), so looping for all possibles strings seems ok. In fact it would seem the cleanest

for (int=0; i
I'm getting the syntax error:

array required but java.lang.String found

for this line:

String pattern = patterns[i];
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial