gpt4 book ai didi

c# - 正则表达式模式只需要匹配第一次出现而不是 "greedy"

转载 作者:行者123 更新时间:2023-11-30 19:52:35 28 4
gpt4 key购买 nike

我被一种模式难倒了,它不断返回第一个之后的所有匹配项(它是“贪婪的”)我的模式:ISS/(?\w\S*)文本有两个匹配项:

ISS/2018-03-02
国际空间站/2005-03-09

我只希望 C# 正则表达式返回第一个匹配项“2018-03-02”

    private static readonly Regex tagIssueDateRegex = new Regex(
@"ISS\/(?<issue>\w+\S*)",
RegexOptions.Singleline);

最佳答案

非贪婪

对于非贪婪算法,我们只需添加一个 s 标志:

ISS\/(\d{4}-\d{2}-\d{2})

DEMO for non-greedy

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})";
string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
RegexOptions options = RegexOptions.Singleline;

Match m = Regex.Match(input, pattern, options);
Console.WriteLine("'{0}' found at index {1}", m.Value, m.Index);
}
}

贪心

我猜我们希望只返回 ISS 的第一个实例后跟一个日期,为此,我们将从一个表达式开始:

ISS\/(\d{4}-\d{2}-\d{2})

然后我们将添加以下表达式之一:

[\s\S]*
[\w\W]*
[\d\D]*
[\s\S].*
[\w\W].*
[\d\D].*

将所有字符和新行滑动到我们字符串的末尾,我们将有:

ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*

如果我正确理解问题。

如有必要,我们可以增加或减少边界。

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"ISS\/(\d{4}-\d{2}-\d{2})[\s\S]*";
string input = @"ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09
ISS/2018-03-02
ISS/2005-03-09";
RegexOptions options = RegexOptions.Multiline;

foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}

DEMO for greedy

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于c# - 正则表达式模式只需要匹配第一次出现而不是 "greedy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56380618/

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