Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple words in a string ln java like php str_replace

I need to find a similar slick way in java to do multi string replace the same way you can do this in php with str_replace.

I want to take a string and then returns a string with the numbers 1 to 10 replaced with the word for those numbers.

"I won 7 of the 10 games and received 30 dollars." => "I won seven of the ten games and received 30 dollars."

In php, you can do:

function replaceNumbersWithWords($phrase) { 

  $numbers = array("1", "2", "3","4","5","6","7","8","9","10");
  $words   = array("one", "two", "three","four","five","six","seven","eight","nine","ten");
  return str_replace($numbers,$words,$phrase);

}

I'm not sure there is an elegant way to do regular expressions on this particular case with String.replace(), and I don't want to use what I feel is a brute force approach to do this: like here: How to replace multiple words in a single string in Java?.

like image 704
Kristy Welsh Avatar asked Jan 13 '14 12:01

Kristy Welsh


1 Answers

You can do that with replaceEach() from StringUtils:

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#replaceEach(java.lang.String, java.lang.String[], java.lang.String[])

StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
like image 175
treeno Avatar answered Sep 21 '22 17:09

treeno