You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何修改字符串仅保留末尾带标点符号的句子

Java 过滤保留带结束标点句子的实现方案
  • 你当前使用的 String.replace() 仅支持固定字符串的精确匹配替换,无法实现这种需要规则判断的文本过滤需求。要实现仅保留带结束标点(./?/!)句子的需求,更推荐用正则匹配提取所有合法句子后拼接的方案,稳定性更高。

推荐实现代码

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

public class FilterValidSentences {
    public static void main(String[] args) {
        String text = "This is some text. I want to keep certain portions of it. I only want to keep sentences with punctuation. This is not an example of a sentence that should be kept This is an example of text that should be kept. How would I do this?";
        // 正则规则:匹配任意非结束标点的字符序列,后跟一个结束标点,兼容标点后的空格/换行
        Pattern validSentencePattern = Pattern.compile("[^.!?]+[.!?]\\s*");
        Matcher matcher = validSentencePattern.matcher(text);
        StringBuilder resultBuilder = new StringBuilder();

        while (matcher.find()) {
            resultBuilder.append(matcher.group());
        }

        // 最终结果,可按需调用trim()去除首尾多余空白
        String filteredText = resultBuilder.toString().trim();
        System.out.println(filteredText);
    }
}

输出结果

执行上述代码后输出内容如下,已自动剔除无结束标点的无效句子:

This is some text. I want to keep certain portions of it. I only want to keep sentences with punctuation. This is an example of text that should be kept. How would I do this?

可选:直接使用replaceAll实现

如果希望用replaceAll方法一行实现,可使用如下写法(稳定性略低于提取方案):

text = text.replaceAll("(?<=\\s|^)[^.!?]+(?=\\s[^.!?])", "").replaceAll("\\s{2,}", " ").trim();

规则扩展说明

如果需要适配中文标点(。/?/!)等其他结束符,只需把正则中的[.!?]替换为[.!?。?!]即可。

内容的提问来源于stack exchange,提问作者Matthew Benchimol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:09:01