Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String split - Regular expression

 
Abi Raj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to split a string into array of strings. the delimiter is ,.

for example the string when splited
"\\ma\\", "g,a", "\"AL","\"wA\"", in, "or"

should return an array of the following strings.

\\ma\\
g,a
\"AL
\"WA\"
in
or

Can I use a regular expression and if so how?

Thanks in Advance.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34372
345
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abi,
You are correct - Java 1.4 and higher have a split method that takes a regular expression:
String[] result = string.split(regExp)

The delimiter is not just a comma in your example though. It looks like it is a comma not surrounded by quotes or a comma followed by a space. I can't tell which one from the example.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your string has to be adjusted for compiling and the closest I get is with the following code



The problem is that the sign \ is an escape karakter in Java.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.coderanch.com/t/379936/java/java/Regular-Expression-Parse-CSV
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic