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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With