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

Java中使用正则表达式筛选指定结尾模式的字符串

Java正则筛选以"WithSuffix+数字"结尾的字符串

直接给你能用的方案:

正则表达式

用这个正则就能精准匹配你的需求:

.*WithSuffix\d+$

拆解一下每个部分的作用:

  • .*:匹配字符串开头到"WithSuffix"之前的任意内容(零个或多个字符)
  • WithSuffix:精确匹配你指定的固定标识
  • \d+:匹配至少一个数字(\d代表0-9的数字,+确保不会匹配空的情况)
  • $:锚定字符串结尾,保证数字后面没有其他杂项(这就是排除stringWithSuffix8notCounted的关键)

Java代码实现

用Stream结合正则来筛选,代码简洁高效:

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FilterStrings {
    public static void main(String[] args) {
        String[] input = {
            "stringWithNoSuffix", 
            "secondString", 
            "stringWithSuffix01", 
            "stringWithSuffix99", 
            "stringWithSuffix8notCounted"
        };

        // 预编译正则,提升复用性能
        Pattern matchPattern = Pattern.compile(".*WithSuffix\\d+$");

        List<String> filtered = Arrays.stream(input)
                .filter(s -> matchPattern.matcher(s).matches())
                .collect(Collectors.toList());

        System.out.println(filtered);
        // 输出结果:[stringWithSuffix01, stringWithSuffix99]
    }
}

关键注意点

  • 必须用matches()方法:它会检查整个字符串是否完全符合正则规则;如果用find(),只要字符串里有匹配片段就返回true,不符合你的筛选要求。
  • 预编译正则:如果需要多次执行筛选逻辑,预编译Pattern比每次直接调用String.matches()更高效,避免重复编译正则表达式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:00:56