• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RegEx question: How to match the character {

 
Martin Wunderlich
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... or simply do:


[ October 12, 2008: Message edited by: Piet Verdriet ]
 
Martin Wunderlich
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic