This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Pattern Matching Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "Pattern Matching" Watch "Pattern Matching" New topic

Pattern Matching

Shan Pyong

Joined: Jul 09, 2006
Posts: 3

I have a string like this:
String s="Cat and or dog and and cow or or or and sheep";

Expected string:
String result="Cat and dog and cow or sheep";

I would like to replace patterns like "and and and..." by a single "and" (same for "or"). Similarly, if there is a pattern like "and or.." or "or and or.." in the string, I want that to be replaced with the first word in the pattern. That is, by "and" , "or" respectively.

String s="Cat and or dog";
Output: Cat and dog
String s="cat or and and dog";
Output: cat or dog

Please let me know how to do handle this. Many thanks for your help.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
This works, but I'm not sure if there's an easier way.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
I agree. Here's the link:
subject: Pattern Matching
jQuery in Action, 3rd edition