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

求助:Java环境下合并满足特定规则的正则表达式方案

合并正则表达式满足双重排除需求

最终正则表达式(Java环境)

直接使用以下正则即可同时满足你的两个排除条件:

String regex = "^[^:*]*\\S[^:*]*$";

正则逻辑拆解

  • ^ 和 $:锚定整个字符串,确保正则匹配完整内容,避免部分匹配导致误判
  • [^:*]*:匹配任意数量(包括0个)不包含:和*的合法字符
  • \S:匹配至少一个非空白字符,直接排除全空白字符串的情况
  • 前后的[^:*]*:保证非空白字符的前后都不会出现被禁止的:或*

验证示例

可通过的字符串

  • "hello world":包含非空白字符且无禁止符号 → 匹配成功
  • "hello":同上 → 匹配成功
  • " test ":包含非空白字符且无禁止符号 → 匹配成功

需拒绝的字符串

  • "hello:world":包含: → 匹配失败
  • "hello*world":包含* → 匹配失败
  • " "/" ":全空白字符,无\S匹配 → 匹配失败

代码示例

import java.util.regex.Pattern;

public class RegexValidation {
    public static void main(String[] args) {
        String regex = "^[^:*]*\\S[^:*]*$";
        Pattern pattern = Pattern.compile(regex);

        // 测试用例
        String[] passCases = {"hello world", "hello", "  test  "};
        String[] failCases = {"hello:world", "hello*world", " ", "   "};

        System.out.println("通过用例验证:");
        for (String s : passCases) {
            System.out.printf("%s → %b%n", s, pattern.matcher(s).matches());
        }

        System.out.println("\n拒绝用例验证:");
        for (String s : failCases) {
            System.out.printf("%s → %b%n", s, pattern.matcher(s).matches());
        }
    }
}

内容的提问来源于stack exchange,提问作者Gordon Pham-Nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:01:58