java - 如何在java中查找和替换某些字符串模式

标签 java regex string

由于从 PDF 进行文本推断,我需要修复一些错误。 我需要替换每种形式的字符串,如下所示:

String example="the sun was shin- ing  and the sky bl- ue";

形式为:

String fixxed="the sun was shining  and the sky blue";

我不是正则表达式方面的专家,我尝试这样做,但这是错误的。

String pattern="([\\w])+([\\-])+([\\s])";
String fixxed = text.replaceAll(pattern, "$1");

一个重要的规范,如果“-”之前的字符是字母(不是空格也不是数字),我只需替换子字符串。

最佳答案

按如下方式进行:

public class Main {
    public static void main(String[] args) {
        String example = "the sun was shin- ing  and the sky bl- ue";
        example = example.replaceAll("\\-\\s+", "");
        System.out.println(example);
    }
}

输出:

the sun was shining  and the sky blue

关于java - 如何在java中查找和替换某些字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62259726/

相关文章:

java - 不能缩短具有大字符串数字的字符串数组

java - 正则表达式或拆分以在 Java 中获取数据

c# - ^([1-9]{1,2},){4}[1-9]{1,2}$ 和 ([1-9]{1,2},){4}[ 有什么区别1-9]{1,2}?

python - 从字符串中读取字节作为 float

python - 为什么 python2 显示\r(原始转义)而 python3 不显示?

java - String HashSet 生成的输出与 String Hash 函数不匹配

java - 异常说明 "Resetting to invalid mark "在标记 inputStream 并重置它时出现,对于大文件。?

java - Java中从字符串中提取数字

javascript - 在 Javascript 中将字符串转换为数组的数组

javascript - 当我提交表单时页面发生变化