Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何在贪婪背后看一看_.net_Regex_Regex Lookarounds_Regex Greedy - Fatal编程技术网

.net 如何在贪婪背后看一看

.net 如何在贪婪背后看一看,.net,regex,regex-lookarounds,regex-greedy,.net,Regex,Regex Lookarounds,Regex Greedy,我正在尝试匹配两个标记/标记之间的文本: -- #begin free text this is the first bit of text I want to match blah blah blah this is the end of the matching text -- #end free text 我已经用下面的.Net正则表达式实现了这一点 (?s)(?<=-- #begin free text\s*)(?<freeText>(.+?))(?=\s+--

我正在尝试匹配两个标记/标记之间的文本:

-- #begin free text

this is the first bit of text I want to match
blah blah blah
this is the end of the matching text

-- #end free text
我已经用下面的.Net正则表达式实现了这一点

(?s)(?<=-- #begin free text\s*)(?<freeText>(.+?))(?=\s+-- #end free text)
(?s)(?使用以下命令:

(?s)(?<=-- #begin free text\s*)\S.*?(?=\s*-- #end free text)
解释

  • (?s)
    激活
    DOTALL
    模式,允许点跨行匹配

  • lookbehind
    (?你真的需要lookarounds吗?这对我很有用:

    Regex r = new Regex(
        @"(?s)-- #begin free text\s+(?<freeText>(.+?))\s+-- #end free text");
    text = r.Match(subjectString).Groups["name"].Value;
    
    Regex r=新的Regex(
    @“(?)-#开始自由文本\s+(.+)\s+-#结束自由文本”);
    text=r.Match(subjectString).Groups[“name”].Value;
    

    Lookarounds在您需要时是非常宝贵的,但大多数时候它们只是妨碍了您。对于.NET正则表达式和其“一切正常”的Lookarounds,这一点要差得多,但它仍然适用。

    FYI:补充说明。:)太好了,是\S做的。我必须修改您的正则表达式以包含组名:(?S)(?)?
    this is the first bit of text I want to match\nblah blah blah\nthis is the end of the matching text
    
    Regex r = new Regex(
        @"(?s)-- #begin free text\s+(?<freeText>(.+?))\s+-- #end free text");
    text = r.Match(subjectString).Groups["name"].Value;