Skip to main content
 首页 » 编程设计

c#之正则表达式 C# 是否可以在替换中使用变量

2024年01月31日29haluo1

我在文本中得到了一堆字符串,看起来像这样:

h1. this is the Header 
h3. this one the header too 
h111. and this 

我得到了函数,它假设处理这个文本取决于它被称为迭代的内容

public void ProcessHeadersInText(string inputText, int atLevel = 1) 

如果被调用,输出应该如下所示

ProcessHeadersInText(inputText, 2) 

输出应该是:

<h3>this is the Header<h3> 
<h5>this one the header too<h5> 
<h9 and this <h9> 

(最后一个看起来像这样,因为如果 h 字母之后的值大于 9,它应该是输出中的 9)

于是,我开始考虑使用正则表达式。

这是例子 https://regex101.com/r/spb3Af/1/

(如您所见,我想出了这样的正则表达式 (^(h([\d]+)\.+?)(.+?)$) 并尝试对其使用替换 <h$3>$4</h$3> )

这几乎就是我要找的东西,但我需要在标题级别的工作中添加一些逻辑。

是否可以在替换中添加任何使用变量的工作?

或者我需要寻找其他方式? (首先提取所有标题,考虑函数变量和标题的值替换em,并且仅在使用我编写的正则表达式之后?)

请您参考如下方法:

您可以使用的正则表达式是

^h(\d+)\.+\s*(.+) 

如果您需要确保匹配不跨行,您可以将 \s 替换为 [^\S\r\n]。查看regex demo .

在 C# 中替换时,将第 1 组值解析为 int 并在 Regex.Replace 方法内的匹配评估器中递增该值。

下面是可以帮助您的示例代码:

using System; 
using System.Linq; 
using System.Text.RegularExpressions; 
using System.IO; 
public class Test 
{ 
    // Demo: https://regex101.com/r/M9iGUO/2 
    public static readonly Regex reg = new Regex(@"^h(\d+)\.+\s*(.+)", RegexOptions.Compiled | RegexOptions.Multiline);  
 
    public static void Main() 
    { 
        var inputText = "h1. Topic 1\r\nblah blah blah, because of bla bla bla\r\nh2. PartA\r\nblah blah blah\r\nh3. Part a\r\nblah blah blah\r\nh2. Part B\r\nblah blah blah\r\nh1. Topic 2\r\nand its cuz blah blah\r\nFIN"; 
        var res = ProcessHeadersInText(inputText, 2); 
        Console.WriteLine(res); 
    } 
    public static string ProcessHeadersInText(string inputText, int atLevel = 1)  
    { 
        return reg.Replace(inputText, m => 
            string.Format("<h{0}>{1}</h{0}>", (int.Parse(m.Groups[1].Value) > 9 ? 
                9 : int.Parse(m.Groups[1].Value) + atLevel), m.Groups[2].Value.Trim())); 
    } 
} 

参见 C# online demo

请注意,我在 m.Groups[2].Value 上使用 .Trim() 作为 . 匹配 \r。您可以使用 TrimEnd('\r') 去除这个字符。