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

如何在同一正则表达式中实现分隔符的含/不含区分并适配多行文本?

问题

你现在用C#的Regex.Split处理字符串,代码如下:

string StringX = TextBoxY.Text;

string[] splicharX = Regex.Split(StringX, @"\s(today.+|but|)\s");

场景1

输入文本:

Today they are really tired but tomorow they will go back to work.

你想要的输出是:

Today they are really tired

场景2

如果把正则改成@"\s(today.+|but|.+back)\s",同样的输入文本,你想要的输出是:

Today they are really tired 
tomorow they will go back

核心需求:要让today.+、.+back这类匹配的内容留在分割结果里,but这类直接排除,还要能适配多行文本。怎么写单行正则实现这个?


解决办法

要搞定这个,关键是利用正则的捕获组和非捕获组的区别,再加上单行模式适配多行,具体思路和代码如下:

正则写法

直接用这个正则就行:

@"(?s)\s+(?:but\s+)|(\s*(?:today.*?|.*?back)\s*)"

完整代码示例

string input = @"Today they are really tired but tomorow they will go back to work.
Another line today starts here and ends back here.";

// 分割+过滤空内容+去首尾空格
var result = Regex.Split(input, @"(?s)\s+(?:but\s+)|(\s*(?:today.*?|.*?back)\s*)")
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .Select(s => s.Trim())
    .ToArray();

// 打印结果
foreach (var piece in result)
{
    Console.WriteLine(piece);
}

正则逻辑解释

  • (?s):开启单行模式,让.能匹配换行符,直接适配多行文本;
  • \s+(?:but\s+):用非捕获组(?:...)包裹but,意思是“匹配到这个就分割,但别把它放进结果里”,\s+处理前后的空格;
  • (\s*(?:today.*?|.*?back)\s*):用捕获组()包裹你想要保留的内容——要么是从today开始的片段,要么是到back结束的片段,.*?是非贪婪匹配,避免吃掉后面的目标内容;
  • 最后用Where和Select清理掉分割出来的空字符串和多余空格,得到干净的结果。

实际效果

对于多行输入:

Today they are really tired but tomorow they will go back to work.
Another line today starts here and ends back here.

输出是:

Today they are really tired
tomorow they will go back
today starts here and ends back

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:15:42