如何只取第一行从多行文本 [英] How to take only first line from the multiline text
本文介绍了如何只取第一行从多行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用正则表达式只得到多行文本的第一行?
字符串测试= @只是借此第一行
甚至有
多一些
线在这里;
匹配M = Regex.Match(测试,^,RegexOptions.Multiline);
如果(m.Success)
Console.Write(m.Groups [0] .value的);
解决方案
字符串测试= @只是借此一线
甚至还出现在这里
多一些
线;
匹配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));
这篇关于如何只取第一行从多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文