Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 760
  • Last Modified:

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

0
galaxy573
Asked:
galaxy573
  • 3
  • 2
1 Solution
 
objectsCommented:
easier to use replaceAll(), why not use that

0
 
galaxy573Author Commented:
Java 1.3 does not have replaceAll() unfortunately.
0
 
objectsCommented:
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
0
 
galaxy573Author Commented:
I'm getting the syntax error:

array required but java.lang.String found

for this line:

String pattern = patterns[i];
0
 
objectsCommented:
patterns should be an array of strings

String[] patterns = new String[] {"&", "\""};

you'll also need an array of replacements

String[] replaces = new String[] {"and", "quote"};

which you will use :

            sb.append(replaces[i]);

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now