java - 如何使用给定的字符串将字符串数字转换为数字,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.
}
解决方案
此建议将您的方法与匹配的正则表达式相匹配,使用Matcher
andPattern
应用正则表达式来提取数字,然后使用方法将每个数字替换为数组中的匹配索引replace()
。
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 中的匹配器循环将简单地将数字字符串替换为方法中内置的名称字符串。
- 循环结束后打印结果。
推荐阅读
- arrays - DispatchWorkItem 不会立即取消任务
- php - 使用公共应用程序将 Xero API 与 Laravel 集成的问题 - 需要手动操作
- javascript - 实施 Polyfill 的问题
- amazon-web-services - AWS Cloudformation 用户数据问题
- jquery - 未捕获的 TypeError:b.ready.promise 不是函数
- remote-debugging - Intershop7 - 远程管道调试 - 客户端未注册异常
- excel - “运行时错误 13:不匹配”错误 - 在 vba 中粘贴
- bixby - 如何在逻辑上使用导航模式
- elasticsearch - ElasticSearch 重新索引原因
- xcodebuild - 从 XCUITest 获取测试类名称和测试名称