更新时间:2023-12-04 13:36:28
字符串测试= @只是借此一线
甚至还出现在这里
多一些
线;
匹配M = Regex.Match(测试,^(*)。,RegexOptions.Multiline);
如果(m.Success)
Console.Write(m.Groups [0] .value的);
。
往往被吹捧为匹配任何字符,虽然这是不完全正确。 。
只匹配,如果你使用 RegexOptions.Singleline
选项的任何字符。如果没有这个选项,它匹配任何字符,除了'\\\
(行尾)。
这就是说,一个更好的选择可能是:
字符串测试= @只是把这个第一行
还送有
多一些
线在这里;
串firstLine中= test.Split(新的String [] {} Environment.NewLine,StringSplitOptions.None)[0];
击>
和更好的,是布赖恩拉斯穆森的版本:
字符串FIRSTLINE = test.Substring(0,test.IndexOf(Environment.NewLine));
How can I get only the first line of multiline text using regular expressions?
string test = @"just take this first line
even there is
some more
lines here";
Match m = Regex.Match(test, "^", RegexOptions.Multiline);
if (m.Success)
Console.Write(m.Groups[0].Value);
string test = @"just take this first line
even there is
some more
lines here";
Match m = Regex.Match(test, "^(.*)", RegexOptions.Multiline);
if (m.Success)
Console.Write(m.Groups[0].Value);
.
is often touted to match any character, while this isn't totally true. .
matches any character only if you use the RegexOptions.Singleline
option. Without this option, it matches any character except for '\n'
(end of line).
That said, a better option is likely to be:
string test = @"just take this first line
even there is
some more
lines here";
string firstLine = test.Split(new string[] {Environment.NewLine}, StringSplitOptions.None)[0];
And better yet, is Brian Rasmussen's version:
string firstline = test.Substring(0, test.IndexOf(Environment.NewLine));