[英]Regex pattern needs to match only the first occurrence and not be “greedy”
我对一个模式感到困惑,它继续返回所有匹配超出第一个(它是“贪婪”)我的模式:ISS /(?\\ w \\ S *)其中文本有两个匹配:
ISS / 2018年3月2日
ISS / 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})
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);
}
}
}
jex.im可视化正则表达式:
使用此模式:
^ISS\/(?<issue>\w+\S*)
如果在第一个“ISS”之前可以有文本,请使用以下文本:
^.*?ISS\/(?<issue>\w+\S*)
^
表示“行的开头”, .*?
表示“任何字符,从0到n次,尽可能少。
请注意,在您的模式中\\w+\\S*
是一个非常广泛的日期匹配部分。
您可以使用您的模式并使用Match来获得第一次出现。
string pattern = @"ISS\/(?<issue>\w\S*)";
string input = @"ISS/2018-03-02
ISS/2005-03-09";
RegexOptions options = RegexOptions.Multiline;
var res = Regex.Match(input, pattern);
Console.WriteLine(res.Value);
结果:
ISS/2018-03-02
如果您想要更具体的匹配日期格式,您可以使用:
\bISS/(?<issue>\d{4}-\d{2}-\d{2})\b
查看正则表达式演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.