gpt4 book ai didi

c# - 一个正则表达式中的多个组?

转载 作者:太空狗 更新时间:2023-10-30 00:24:29 25 4
gpt4 key购买 nike

我试图在 .NET 中匹配同一 Regex 对象中的两个组,因此我可以分别处理它们;我不想为每个单独的表达式实例化许多对象。基本上,我想在句号前插入下划线,在感叹号前插入破折号。现在,我知道我可以使用标点符号结构,但我想将每个组用作单独的表达式。

这是我尝试过的数百万种方法的变体:

using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var rule = new Regex(@"(\.)(\!)", RegexOptions.Compiled);
var myText = "string. will! way. water! test. quiz! short. long!";
richTextBox1.Text = rule.Replace(rule.Replace(myText, "_$1"), "-$2");
}
}
}

提前致谢。

最佳答案

这应该有效。它使用 Lamba,但如果您想要更多控制权,可以将其分解为一个函数。 Match 委托(delegate)可以是其中之一。基本上,正则表达式引擎会在每次匹配时调用您的委托(delegate),传递匹配的值,因此您可以即时决定如何处理它。

Regex.Replace("Test a. b!", @"([.!])",
(m) => { return m.Value == "." ? "_." : "-!"; }
);

关于c# - 一个正则表达式中的多个组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com