【问题标题】:Replace multiple words in a string ln java like php str_replace替换字符串 ln java 中的多个单词,如 php str_replace
【发布时间】:2014-02-01 05:36:46
【问题描述】:

我需要在 java 中找到一种类似的巧妙方法来执行多字符串替换,就像在 php 中使用 str_replace 执行此操作一样。

我想获取一个字符串,然后返回一个字符串,其中数字 1 到 10 替换为这些数字的单词。

“我赢了 10 场比赛中的 7 场,获得了 30 美元。” => “我赢了十场比赛中的七场,获得了 30 美元。”

在php中,你可以这样做:

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);

}

我不确定是否有一种优雅的方法可以使用 String.replace() 在这种特殊情况下执行正则表达式,并且我不想使用我认为是蛮力的方法来执行此操作:就像这里: How to replace multiple words in a single string in Java?

【问题讨论】:

标签: java php regex string


【解决方案1】:

也许你可以这样替换:

    Map<String, String> replaceMap = new HashMap<String, String>();
    replaceMap.put("1","one");
    replaceMap.put("2","two");
    replaceMap.put("3","three");
    replaceMap.put("4","four");
    String str = "aaa1ss2";
    for (Map.Entry<String, String> entry : replaceMap.entrySet()) {
        str = str.replaceAll(entry.getKey(), entry.getValue());
    }

【讨论】:

    【解决方案2】:

    您可以使用 StringUtils 中的 replaceEach() 来做到这一点:

    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"
    

    【讨论】:

    • 接受这个答案,但也想为此给予 pomkine 功劳。
    • 抱歉没有注意到,pomkine 更快:+1 @pomkine
    猜你喜欢
    • 2016-10-08
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2012-06-12
    相关资源
    最近更新 更多