gpt4 book ai didi

java - 字符序列与正则表达式

转载 作者:行者123 更新时间:2023-11-30 05:27:43 25 4
gpt4 key购买 nike

txt.replaceAll("a","b"); 

“a”是字符序列还是正则表达式(或更具体的文字搜索)?

我的代码正确吗?我正在编写练习“规范化文本”。任务:

  • 单词之间只有一个空格。
  • 逗号 (,)、点 (.) 和冒号 (:) 后只能有一个空格。第一的点后单词的字符为大写,其他单词为小写。
<小时/>

如果我错了,包括我的英语,请纠正我。

public class NormalizeText {

static String spacesBetweenWords(String txt){
txt = txt.replaceAll(" +", " ");
return txt;
}

/**
* - There are no spaces between comma or dot and word in front of it.
* - Only one space after comma (,), dot (.) and colon (:).
*/
static String spacesCommaDotColon(String txt) {
txt = txt.replaceAll(" +\\.", ".");
txt = txt.replaceAll(" +,", ",");
txt = txt.replaceAll(" +[:]", ":");
txt = txt.replaceAll("[.]( *)", ". ");
txt = txt.replaceAll("[,]( *)", ", ");
txt = txt.replaceAll("[:]( *)", ": ");
//txt.replaceAll("a","b");

return txt;
}

public static void main(String[] args) {
// TODO code application logic here
String txt = "\" \\\" i want to f\\\"ly\" . B.ut : I , Cant\\";
System.out.println(txt);
txt = spacesBetweenWords(txt);
System.out.println(spacesBetweenWords(txt));
System.out.println(spacesCommaDotColon(txt));
}

}

我的老师说我的代码没有使用正则表达式,而是使用字符序列。我很困惑。

最佳答案

对于初学者来说,因为您学习如何使用正则表达式,所以学习如何使用正则表达式的一个很棒的网站是 this 。现在,replaceAll 第一个参数算作正则表达式。仅字母“a”是仅匹配文本内的“a”的正则表达式。所以你的老师的意思可能是使用更复杂的正则表达式(一次匹配多个案例的东西)。由于这是一个练习,我不想给出解决方案,因此您将尝试自己解决。提示是尝试仅使用 replaceAll 一次。!或者你可以更接近一次。

至于你的代码是否正确。看起来不错,但点条件后缺少大写字母。另外,因为我说过尝试仅使用一个 replaceAll,所以大写的解决方案不算在内,因为它需要其他方法。

我希望我有所帮助,您会找到练习的解决方案,再次抱歉没有提供练习的答案,但在我看来,您需要尝试自己解决。你已经走在一条好的路上了!

关于java - 字符序列与正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219810/

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