Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Splitting a string on an ampersand (&) character

Status
Not open for further replies.

ackitsme

IS-IT--Management
Oct 15, 2002
21
US
I have need to split a string based on an ampersand character.

I've tried the following code:
Code:
String[] result = mystring.split("&");
but it returns a JasperException error.

I've tried using "\&" but it tells me that it's an illegal escape character.

Is there a (hopefully) easy way to do this without having to resort to writing a separate function for it?

Thanks in advance


-------------------------------------------------------------------------
Charlie Silverman
Sr. Systems Administrator
Globalstar, LLC

-------------------------------------------------------------------------
We now return you to your regularly scheduled reality.
 
you can use a StringTokenizer for this kind of job like this :
Code:
StringTokenizer st = new StringTokenizer("mystring", "&");
while (st.hasMoreTokens()) {
  System.out.println(st.nextToken());
}

Water is not bad as long as it remains outside human body ;-)
 
I've never spent a lot of time with RegEx, which was really the problem here.

The String.split() command expects a regex parameter. The ampersand character by itself is not a valid regex parameter.

I did some digging and found that the correct way to do that within a regex is '\u0026'.

-------------------------------------------------------------------------
Charlie Silverman
Sr. Systems Administrator
Globalstar, LLC

-------------------------------------------------------------------------
We now return you to your regularly scheduled reality.
 
Sounds a bit strange to me. Ampersands are perfectly valid regexp characters. The following works perfectly for me (Java 1.5):
Code:
String blah = "first&second&third&fourth";
String[] stuff = blah.split( "&" );
for ( int i = 0; i < stuff.length; i++ ) {
        System.out.println( stuff[i] );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top