首页 > 解决方案 > 如何使用给定的字符串将字符串数字转换为数字,Java

问题描述

我想从给定的字符串句子中提取数字并转换为数值。例如,

输入:“您好,我有两个密码,分别是 dk12kdkd 和 2kdkae5。”

输出:“您好,我有两个密码,分别是 dkONETWOkdkd 和 TWOkdkaeFIVE。”

我对如何提取数字和更改值以取回原始数字感到困惑。

谢谢您的帮助!

public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");


  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};


    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}

标签: java

解决方案


此建议将您的方法与匹配的正则表达式相匹配,使用MatcherandPattern

应用正则表达式来提取数字,然后使用方法将每个数字替换为数组中的匹配索引replace()

在线演示 http://tpcg.io/qYIn6e6h

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    static String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    public static void main(String[] args) {

        String regex = "(\\d+)";
        String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(testString);

        while ( matcher.find() ) {
            testString = testString.replaceFirst(matcher.group(1), getDigitsText(matcher.group(1)) );
        }
        System.out.println( testString);
    }

 /**
 * Gets the text representation of the given number.
 * Example:  Input: 39 outputs: THREENINE
 */
    public static String getDigitsText( String digitText ){
        //split digits if more than one digit. split("") works since Java 8
        String[] digitStrings = digitText.split("");
        //get digit for string
        String text = "";
        for (String digitString : digitStrings){
            //parase string to int
            int digit = Integer.parseInt(digitString);
            //get matching text from 
            text += singleDigits[digit];
        }

        return text;
    }
}

输出:

您好,我有两个密码,分别是 dkONETWOkdkd 和 TWOFIVEkdkaeFIVE。

方法

  • 使用 Matcher 和 Pattern 使用正则表达式 (\d+) 从字符串中提取数字
  • 正则表达式返回该字符串中的每个数字部分,它可能是多个数字。
  • 此方法getDigitsText()将获取该字符串,将其拆分为一个字符串数组,每个元素代表一个必须是数字的字符。
  • 然后迭代数组,从数组中获取数字的singleDigits[]名称
  • 该方法连接名称并返回给定数字的文本表示。
  • main 中的匹配器循环将简单地将数字字符串替换为方法中内置的名称字符串。
  • 循环结束后打印结果。

推荐阅读