java - 将小数点 1 到 10 替换为名称 ("one", "two"..)

标签 java regex string

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

I won 7 of the 10 games and received 30 dollars.

应该变成:

I won seven of the ten games and received 30 dollars.

所以我这样做了:

import org.apache.commons.lang3.StringUtils;

String[] numbers = new String[] {"1", "2", "3","4","5","6","7","8","9","10"};
String[] words   = new String[]{"one", "two", "three","four","five","six",
    "seven","eight","nine","ten"};
System.out.print(StringUtils.replaceEach(phrase, numbers, words));

结果是这样的:

I won seven of the one0 games and received three0 dollars.

所以我尝试了一种蛮力方式,我确信可以通过正则表达式或更优雅的字符串操作来改进它:

public class StringReplace {

  public static void main(String[] args) {
    String phrase = "I won 7 of the 10 games and received 30 dollars.";
    String[] sentenceWords = phrase.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String s: sentenceWords) { 
      if (isNumeric(s)) { 
        sb.append(switchOutText(s));
      }

      else { 
        sb.append(s);
      }
      sb.append(" ");

    }
    System.out.print(sb.toString());
  }

  public static String switchOutText(String s) { 
    if (s.equals("1"))
      return "one";
    else if (s.equals("2"))
      return "two";
    else if (s.equals("3"))
      return "three";
    else if (s.equals("4"))
      return "four";
    else if (s.equals("5"))
      return "fivee";
    else if (s.equals("6"))
      return "six";
    else if (s.equals("7"))
      return "seven";
    else if (s.equals("8"))
      return "eight";
    else if (s.equals("9"))
      return "nine";        
    else if (s.equals("10"))
      return "ten";
    else
      return s;        
  }

  public static boolean isNumeric(String s) { 
    try { 
      int i = Integer.parseInt(s);
    }
    catch(NumberFormatException nfe) { 
      return false;
    }
    return true;
  }

}

有没有更好的办法?对正则表达式建议特别感兴趣。

最佳答案

这种方法使用正则表达式来匹配被非数字包围的目标数字(或开始或结束字符):

String[] words = { "one", "two", "three", "four", "five", "six", "seven",
    "eight", "nine", "ten" };
String phrase = "I won 7 of the 10 games and received 30 dollars.";

for (int i = 1; i <= 10; i++) {
  String pattern = "(^|\\D)" + i + "(\\D|$)";
  phrase = phrase.replaceAll(pattern, "$1" + words[i - 1] + "$2");
}

System.out.println(phrase);

这打印:

I won seven of the ten games and received 30 dollars.

如果数字是句子中的第一个或最后一个单词,它也会处理。例如:

9 cats turned on 100 others and killed 10

正确翻译成

nine cats turned on 100 others and killed ten

关于java - 将小数点 1 到 10 替换为名称 ("one", "two"..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094049/

相关文章:

java - 使用 Hibernate 和 dom4j,是否可以在没有 DB 的情况下将 POJO 转换为其 XML 表示(反之亦然)?

java - Confluence Schema Registry 如何管理本地缓存

java - Java 中的链接错误

python - 在 Python 中添加字母数字中的正则表达式

c++ - 由字符串而不是整数值索引的矩阵

Tomcat负载均衡环境下Java应用间通信

javascript - 连接数组值

javascript - 当输入类型 ="number"时,正则表达式验证是否有效?

java - 使用带有字符串的 Luhn 算法在 Java 中进行信用卡验证

Python 比较列表中的部分字符串