Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2005

Tip: Looking for answers? Try searching our database.

Splitting a String on space with possible Quotes

Thread view: 
rcurts - 14 Jun 2005 02:27 GMT
I'm having trouble finding a regular expression to do what I want.

I get a string that I want to split by spaces, and the tokens may or
may not be encapsulated by quotes.

I would like to take:

DOG CAT "LAUGHING HYENA" BIRD
and get

0: DOG
1: CAT
2: LAUGHING HYENA
3: BIRD

I won't know if a token will come through encapsulated by quotes or
not.  I was thinking of looping through each char in the string, but I
can only hope there's a better way to do this.

Any ideas?

Thanks
rcurts
shakah - 14 Jun 2005 04:49 GMT
> I'm having trouble finding a regular expression to do what I want.
>
[quoted text clipped - 19 lines]
> Thanks
> rcurts

There's got to be a better way, but how about
something like '"([^"]*)"| ?([^ ]+) ?' ?

jc@sarah:~/tmp$ cat regextest3.java
public class regextest3 {
 public static void main(String [] asArgs) {
   java.util.regex.Pattern p =
java.util.regex.Pattern.compile(asArgs[0]) ;
   for(int nArg=1; nArg<asArgs.length; ++nArg) {
     System.out.println("looking in '" + asArgs[nArg] + "'") ;
     java.util.regex.Matcher m = p.matcher(asArgs[nArg]) ;
     while(m.find()) {
       for(int i=0; i<m.groupCount(); ++i) {
         String sTemp = m.group(i+1) ;
         if(null!=sTemp) {
           System.out.println("  found: '" + sTemp + "'") ;
         }
       }
     }
   }
 }
}

jc@sarah:~/tmp$ /usr/java/jdk1.5.0_01/bin/java regextest3 '"([^"]*)"|
?([^ ]+) ?' 'DOG ""  CAT "LAUGHING HYENA" BIRD'
looking in 'DOG ""  CAT "LAUGHING HYENA" BIRD'
 found: 'DOG'
 found: ''
 found: 'CAT'
 found: 'LAUGHING HYENA'
 found: 'BIRD'


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.