aspose file tools*
The moose likes Java in General and the fly likes Help with Regular Expressions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Help with Regular Expressions" Watch "Help with Regular Expressions" New topic
Author

Help with Regular Expressions

Philippe Desrosiers
Ranch Hand

Joined: Mar 29, 2006
Posts: 138
Can anyone tell me how to get the replacement text for each matcher capturing group?

example: I want to replace "WARM tamales" with "WARMER tamales", using the search pattern "(HOT|COLD|WARM|)" and the replacement pattern "$1ER". This works fine, but I also want to be able to discover what was the final replacement text used for capturing group 1 (eg. in this example, it would be the text WARMER, which replaced the original text WARM).

Does this make sense? Can it be done?

PLEASE HELP!

edit: oh yeah, here's some code...


edit: Fixed the comments in the code (thanks Rob!)
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

The replaceAll() method is merely a convenience method that uses the lower level find(), appendReplacement(), and appendTail() methods. An option is to not use replaceAll(), but use the lower level methods directly, to do the replacement, and to save a copy of the replacement.

The javadoc for the append methods has an example of how the three methods work together...

http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

I copied your code exactly as it is, and for me it printed "results: WARMER tamales".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Philippe Desrosiers
Ranch Hand

Joined: Mar 29, 2006
Posts: 138
Rob Prime wrote:I copied your code exactly as it is, and for me it printed "results: WARMER tamales".


Yep. That's the correct result. The comments in the code were wrong (typo). Sorry.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help with Regular Expressions