• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about String operation

 
david arnold
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21417
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
david arnold
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21417
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 "".
 
david arnold
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Marc and Henry for your recommendation and help! Appreciate it!

Regards.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic