aspose file tools*
The moose likes Java in General and the fly likes RegEx question: How to match the character { Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "RegEx question: How to match the character {" Watch "RegEx question: How to match the character {" New topic
Author

RegEx question: How to match the character {

Martin Wunderlich
Greenhorn

Joined: May 06, 2006
Posts: 9
Hi all,

I am trying to write a RegEx Pattern to replace the MessageFormat variables in a properties string (e.g. "My name is {0}" should be changed to "My name is <ph id="0">{0}</ph>".

What seemed like a straighforward task, is getting more complicated, because there seems to be no way to match the { character. I have tried the following, but they all get me errors:



Also, if anyone knows of a straighforward way to extract the number in the MsgFormat variable and use it as the value of the id attribute, I would be very grateful.

Thanks a lot in advance.

Cheers,

Martin
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19695
    
  20

In regular expressions you need to use \ as the escape character, but you also need to escape it for Java. So in the end it would be \\{ inside your string.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You can also use \Q{\E, but the safest route is to use Pattern.quote("{"); to do the quoting for you.

To get the id in the center of the brackets out you would want to put the part of the regex that matches the numbers inside a group (surrounded by parenthesis). You could then use the classes inside java.util.regex package to find the pattern, pull out the number, and replace the text. Example:

[ October 11, 2008: Message edited by: Steve Luke ]

Steve
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
... or simply do:


[ October 12, 2008: Message edited by: Piet Verdriet ]
Martin Wunderlich
Greenhorn

Joined: May 06, 2006
Posts: 9
Thank you so much everyone for the great help! I really, really appreciate it. In the end, I went with Piet's solution, which is doing exactly what I wanted.
Thanks a lot!

Cheers,

Martin
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
Originally posted by Martin Wunderlich:
Thank you so much everyone for the great help! I really, really appreciate it. In the end, I went with Piet's solution, which is doing exactly what I wanted.
Thanks a lot!

Cheers,

Martin


You're welcome Martin!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: RegEx question: How to match the character {