Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with Regular Expressions

 
Philippe Desrosiers
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21405
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 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
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I copied your code exactly as it is, and for me it printed "results: WARMER tamales".
 
Philippe Desrosiers
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic