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

C#正则表达式如何排除特定字符与指定独立单词?

C#正则表达式:匹配单词/数字并排除指定字符与独立单词

根据你的需求,需要匹配所有单词、数字,同时排除&、,以及独立的and/And/AND单词,以下分两种常见场景给出解决方案:

场景1:验证整个字符串是否符合要求

如果你需要判断整个字符串不包含&、,,且没有独立的and(大小写无关)单词,可以使用结合负向前瞻的正则:

// 正则表达式,配合IgnoreCase忽略大小写
string pattern = @"^(?!.*\b(and)\b)[^&,]+$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

表达式解释:

  • ^:匹配字符串起始位置
  • (?!.*\b(and)\b):负向前瞻,确保整个字符串中不存在独立的and单词(\b是单词边界,避免匹配sand这类包含and的非独立词)
  • [^&,]+:匹配任意数量的非&、,的字符
  • $:匹配字符串结束位置

场景2:从文本中提取符合要求的单词

如果你需要从一段文本中提取所有合法的单词/数字(排除&、,和独立的and),可以使用以下正则:

string pattern = @"\b(?!(and)\b)\w+";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

表达式解释:

  • \b:匹配单词边界,确保提取的是独立单词
  • (?!(and)\b):负向前瞻,排除独立的and单词
  • \w+:匹配字母、数字、下划线(如果需要排除下划线,可以改成[a-zA-Z0-9]+)

你原有表达式的问题分析

你之前尝试的"\b(?!and|AND|And\b)\w+"存在两个问题:

  1. 负向前瞻的边界位置错误:(?!and|AND|And\b)会导致前瞻只检查And后的单词边界,逻辑混乱,正确写法应该是(?!and\b)配合IgnoreCase选项,无需重复写三种大小写形式
  2. 如果是验证整个字符串,没有结合排除&、,的逻辑,需要将负向前瞻和[^&,]+结合使用

代码示例

验证字符串的完整示例

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string pattern = @"^(?!.*\b(and)\b)[^&,]+$";
        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        
        string[] testCases = {
            "HelloWorld123",
            "Hello and World",
            "Hello, World",
            "Hello & World",
            "sandwich123",
            "TestANDTest"
        };
        
        foreach (string test in testCases)
        {
            Console.WriteLine($"「{test}」 是否合法:{regex.IsMatch(test)}");
        }
    }
}

提取单词的完整示例

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hi and Hello, this is AND a test & with sandwich And";
        string pattern = @"\b(?!(and)\b)\w+";
        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        
        foreach (Match match in regex.Matches(input))
        {
            Console.WriteLine(match.Value);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:27:36