第一页的正则表达式
Regex for first page
第一页的正则表达式?
分页符 \f
之前的所有内容
这只找到第一页的最后一行
"end of page one"
我需要全部 4 行
"first page"
"second line"
"search string"
"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)(<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";
或
string pattern = @"(.*?)\f";
Match match = Regex.Match(input, pattern, RegexOptions.Singleline);
注意 :- 你还需要使用 .*?
让你的正则表达式变得懒惰
解决方案 2
如果你愿意,你也可以使用 [\S\s]*?
,虽然它会很低效。
旁注
字符class本身作为字符的交替。所以使用 |
不会充当 OR
但会按字面意思匹配 |
。
第一页的正则表达式?
分页符 \f
这只找到第一页的最后一行
"end of page one"
我需要全部 4 行
"first page"
"second line"
"search string"
"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)(<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";
或
string pattern = @"(.*?)\f";
Match match = Regex.Match(input, pattern, RegexOptions.Singleline);
注意 :- 你还需要使用 .*?
解决方案 2
如果你愿意,你也可以使用 [\S\s]*?
,虽然它会很低效。
旁注
字符class本身作为字符的交替。所以使用 |
不会充当 OR
但会按字面意思匹配 |
。