第一页的正则表达式

本文关键字:正则表达式 第一页 | 更新日期: 2023-09-27 17:49:00

第一页的正则表达式?
直到换行符'f

这只查找第一页的最后一行
"end of page one"

我需要全部4行
"第一页"
"二线"
"搜索字符串"
"end of page one"

添加's并没有为我修复它
['s| s]只是遍历'f并找到所有

string input = "first page" + Environment.NewLine +
               "second line" + Environment.NewLine +
               "search string" + Environment.NewLine +
               "end of page one'f" +
               "second page" + Environment.NewLine +
               "second line" + Environment.NewLine +
               "search string" + Environment.NewLine +
               "end of page two'f";
public string Input { get { return input; }}
public string FirstPage
{
    get
    {
        //@"((.*)'f)'1(<SEARCH STRING GOES HERE>)"); this is what in the end I need to do
        string pattern = @"(.*)'f";
        Match  match = Regex.Match(input, pattern, RegexOptions.Multiline);
        if (match != null)
        {
            return match.Value;
        }
        else
            return "noot found";    
    }
}

第一页的正则表达式

.不匹配换行字符,除非您使用Singleline选项。使用像'W'w这样的集合来匹配任何字符,或者将选项更改为Singleline

*乘数之后使用?使其不贪婪,否则它将匹配所有内容,然后跟踪到最后一个'f

string pattern = @"(['W'w]*?)'f";
Match  match = Regex.Match(input, pattern, RegexOptions.Multiline);

或:

string pattern = @"(.*?)'f";
Match  match = Regex.Match(input, pattern, RegexOptions.Singleline);

方案1

正如在评论中指出的,我认为你需要内联(?s)修饰符或RegexOptions.Singleline选项来允许.匹配新行。

string pattern = @"(?s)(.*?)'f";
<<p> Ideone演示/strong>

string pattern = @"(.*?)'f";
Match  match = Regex.Match(input, pattern, RegexOptions.Singleline);
<<p> Ideone演示/strong>

注意:-你还需要使用.*?

使你的正则表达式懒惰

解决方案2

如果你愿意,你也可以使用['S's]*?,尽管它将是低效的。

边注

字符类本身作为字符的替代。因此,使用|将不作为OR,但将匹配|字面上。