split() in String: asterisk in character class

M

Michael

Hello!

I have the following string Id like to split:
023876:adm;Hansen,Hans-250000*1997

String regexp="[:;,-*]";
givess me an error :
java.util.regex.PatternSyntaxException: Illegal character range near index 5

String regexp="[:;,-\*]";
wont even compile.

How do I express this character class?

Thanks

Michael
 
A

Andrew Thompson

M

Michael Preminger

Michael said:
Hello!

I have the following string Id like to split:
023876:adm;Hansen,Hans-250000*1997

String regexp="[:;,-*]";
givess me an error :
java.util.regex.PatternSyntaxException: Illegal character range near index 5

String regexp="[:;,-\*]";
wont even compile.

How do I express this character class?

Thanks

Michael

O.K. I found the problem:
Java takes ",-*" this as a range (komma to asterisk) and fails to
understand. reshuffling ",*-" solves the problem.

Michael
 
C

Chris Smith

Michael said:
String regexp="[:;,-*]";
givess me an error :
java.util.regex.PatternSyntaxException: Illegal character range near index 5

String regexp="[:;,-\*]";
wont even compile.
Java takes ",-*" this as a range (komma to asterisk) and fails to
understand. reshuffling ",*-" solves the problem.

That's rather fragile, though. Try this instead:

String regexp = "[:;\\,\\-\\*]";

I've escaped the comma, hyphen, and star to avoid their interpretation
as special characters. The tricky part is that since '\' is a special
character to the Java language, it needs to be escaped itself.

It's important to note that the "\\" resolution happens in the compiler,
and has nothing to do with regular expressions. For example, if you
were writing this same regexp in a properties file to be loaded by your
program, you might write:

sep.regexp = [:;\,\-\*]

Hope that makes sense.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top