gpt4 book ai didi

java - 将数字替换为java中正确位置的单词

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:58 29 4
gpt4 key购买 nike

实际上,我正在尝试将数字替换为用户给出的句子中的单词。本例日期格式;例如:我的生日是 16/6/2000,我是 java 的新手 --> become ---> 我的生日是 2000 年 7 月 16 日,我是 java 的新手

代码如下:

        Scanner reader = new Scanner(System.in);
System.out.println("Enter any numbers: ");
String nom = reader.nextLine(); // get input from user

//checking contains that has "/" or not
if(nom.contains("/")){
String parts[] = nom.split("[/]");
String part1 = parts[0]; //data before "/" will be stored in the first array
String day[] = part1.split("\\s+");// split between space
String get_day = day[day.length -1];// get last array

String get_month = parts[1]; //data in the between of "/" will be stored in the second array

String part3 = parts[2]; // data after "/" will be stored in the third array
String year[] = part3.split("\\s+");// split between space
String get_year = year[0];// get first array

String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));

String con = nom.replaceAll("[0-9].*/[0-9].*/[0-].*", s); // replace number to word
System.out.println(con); // print the data already converted
} else {....}

但是我得到的结果是:

My birthday is on sixteenth july two thousand 

//"and I'm newbie to the java" is disappear [How to solve it]//

如何解决。实际上我想获取“/”斜杠前后的值并将其转换为单词并将其替换为用户的原始输入。

我试过的是:

String con = nom.replaceAll("[0-9].*/[0-9].*/[0-9999]", s); // a bit change [0-9].* to [0-9999] 

但是输出变成这样:

My birthday is on sixteenth july two thousand 000 and I'm newbie to the java
//after two thousand index "000" is appearing

最佳答案

正则表达式错误:

[0-9].*/[0-9].*/[0-].*

含义:

[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-] match a single number in the list 0- literally
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]

应该是:

[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]

或者,更好的是:

\d{2}/\d{2}/\d{4}

关于java - 将数字替换为java中正确位置的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052616/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com