File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes A question about String operation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A question about String operation" Watch "A question about String operation" New topic
Author

A question about String operation

david arnold
Ranch Hand

Joined: Apr 10, 2009
Posts: 129
Hi,

I have a string pattern like this: (--Select--)|(word1)|(word2)|(word3), it can has more or less word, for example:

I want to get the "word" and put them in a String[], desired result would be like pattern[0] = --select--, pattern[1] = Business, pattern[2]= Personal, I tried String.replace and String.split to get rid of "|, (, )", but did not work out. When I used , in stead of getting (--Select--), (Business) and (Personal), I got 35 strings. Please help to figure out how to solve this.

Thanks!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39


The split() method takes a regular expression. And in a regular expression, the "|" has special meaning. If you want it to mean the literal "|" (ie. disable the meaning), then you need to escape it... like so...



Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
david arnold
Ranch Hand

Joined: Apr 10, 2009
Posts: 129
I see, thank you Henry for your help.

One more question, when i tried or , both method got exception, i just want to get rid of all ( and ) in the string easily using one operation. What was wrong with it. Thanks.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

The replace() method should work. The replaceAll() method, like the split() method, takes a regex -- and the "(" has special meaning, in a regex.

I really recommend that you read up on regexes, it is really a powerful tool. And going to a forum to figure out the regex to create for the replaceAll() methods is not very effective.

Henry
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See the API documentation for java.util.regex.Pattern.

This will explain when and how to escape special characters, as well as how to capture '(' OR ')' and replace these with empty Strings "".


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
david arnold
Ranch Hand

Joined: Apr 10, 2009
Posts: 129
Thank you Marc and Henry for your recommendation and help! Appreciate it!

Regards.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A question about String operation
 
Similar Threads
Business Patterns
you are my last resort for this question
failure to activate a Web application with database
help on pattern.compile
Manipulating a text file