Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all #{key} in string?

Tags:

java

regex

I have text with multiple #{key} phrases. For example:

Lorem ipsum dolor sit amet, consectetur adipisicing #{key1}. Proin nibh 
augue, suscipit a, scelerisque #{key1}, lacinia in, mi. Cras vel #{key2}. 
Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. 
Quisque semper #{key3} at risus.

I need to replace all #{key} values with corresponding messageSource.getMessage(key, null, locale) (messageSource is org.springframework.context.MessageSource), but i'm not good at regex. How to build right regular expression ?

Examples:

#{texts.appName} need to replace with messageSource.getMessage("texts.appName", null, locale);
#{my.company} need to replace with messageSource.getMessage("my.company", null, locale);
like image 795
marioosh Avatar asked Nov 28 '11 09:11

marioosh


People also ask

How do I find and replace all in word?

Alternatively, use the keyboard shortcut Ctrl+H. Type the word or phrase you're looking for in the "Find what" box, and the replacement word or phrase in the "Replace with" box. Word will take you to the first instance of the word or phrase.

What do the Replace All () do?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

What is replace all in word?

Type the word you need to replace in the Replace with text field. Select a replacement option. Replace: Replaces the first instance of the word. Keep clicking to fix them one at a time. Replace All: Fixes all instances of the word at once.


1 Answers

Assuming key is just a placeholder for any name your regex would be something like this: #\{([\w\.]+)\}

This means: any sequence of word characters or dots (\w\., which is equivalent to a-zA-Z0-9_\.) between #{ and } is returned as group 1.

Now you need to create a matcher and iterate over the matches, extract the key and replace the match with your message:

String input = "Lorem ipsum dolor sit amet, consectetur adipisicing #{key1}. " +
   "Proin nibh augue, suscipit a, scelerisque #{key1}," + 
   "lacinia in, mi. Cras vel #{key2}. Etiam pellentesque aliquet tellus." + 
   " Phasellus pharetra nulla ac diam. Quisque semper #{key3} at risus.";
StringBuffer result = new StringBuffer();

Pattern p = Pattern.compile( "#\\{([\\w\\.]+)\\}" );
Matcher m = p.matcher( input );

while( m.find() ) {      
  //extract the message for key = m.group( 1 ) here
  //i'll just mark the found keys 
  m.appendReplacement( result,  "##" + m.group( 1 ) + "##" );      
}
m.appendTail( result );

System.out.println(result); //output: ... consectetur adipisicing ##key1## ...  etc.
like image 188
Thomas Avatar answered Oct 12 '22 07:10

Thomas