Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace formatted properties inside Java string

Tags:

java

string

regex

I will be given Strings that contain formatted "properties"; that is, Strings encapsulated inside the standard "${" and "}" tokens:

"This is an ${example} of a ${string} that I may be ${given}."

I will also have a HashMap<String,String> containing substitutions for each possible formatted property:

HashMap Keys           HashMapValues
===========================================
bacon                  eggs
ham                    salads

So that, given the following String:

"I like to eat ${bacon} and ${ham}."

I can send this to a Java method that will transform it into:

"I like to eat eggs and salads."

Here's my best attempt:

System.out.println("Starting...");

String regex = "$\\{*\\}";
Map<String,String> map = new HashMap<String, String>();
map.put("bacon", "eggs");
map.put("ham", "salads");

String sampleString = "I like ${bacon} and ${ham}.";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sampleString);
while(matcher.find()) {
    System.out.println("Found " + matcher.group());

    // Strip leading "${" and trailing "}" off.
    String property = matcher.group();

    if(property.startsWith("${"))
        property = property.substring(2);
    if(property.endsWith("}"))
        property = property.substring(0, property.length() - 1);

    System.out.println("Before being replaced, property is: " + property);

    if(map.containsKey(property))
        property = map.get(property);

    // Now, not sure how to locate the original property ("${bacon}", etc.)
    // inside the sampleString so that I can replace "${bacon}" with
    // "eggs".
}

System.out.println("Ending...");

When I execute this, I get no errors, but just see the "Starting..." and "Ending..." outputs. This tells me that my regex is incorrect, and so the Matcher isn't able to match any properties.

So my first question is: what should this regex be?

Once I'm past that, I'm not sure how to perform the string replace once I've changed "${bacon}" into "eggs", etc. Any ideas? Thanks in advance!

like image 303
IAmYourFaja Avatar asked Jun 27 '13 17:06

IAmYourFaja


People also ask

How do I find and replace a character in a string in Java?

Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a character at a specific index – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.

How do you replace %s in Java?

find()){ str = str. replace(m. group(0), "%s"); } System. out.


1 Answers

Why don't use a .properties file?, that way you could get all your messages from that file and could be separate from your code, something like (file example.properties):

message1=This is a {0} with format markers on it {1}

And then in your class load your bundle and use it like this:

ResourceBundle bundle = ResourceBundle.getBundle("example.properties", Locale.getDefault());
MessageFormat.format(bundle.getString('message1'), "param0", "param1"); // This gonna be your formatted String "This is a param0 with format markers on it param1"

You could use the MessageFormat (is a java.util library) without the bundle (just use the String directly), but again, having a bundle makes your code clear (and gives easy internationalization)

like image 118
rekiem87 Avatar answered Nov 02 '22 23:11

rekiem87