简体   繁体   English

C#RegEx匹配第二行中的所有内容

[英]C# RegEx to match all in the second line

I need a regex to match all in the second line. 我需要一个正则表达式来匹配第二行中的所有内容。

First Line
Second Line

I have tried using \\n(.*)\\n but it returns the empty value. 我尝试使用\\ n(。*)\\ n,但它返回空值。

Match match in Regex.Matches(line, @"\n(.*)\n", RegexOptions.Multiline)

You don't need regex for that. 您不需要正则表达式。 Just split input string on lines and get line which you need: 只需在行上分割输入字符串并获取所需的行:

var line= @"First Line
Second Line";

var secondLine = line.Split('\n')[1]; // "Second Line"

You can also check count of lines in your string before getting required line by index to avoid IndexOutOfRange exception. 您还可以在按索引获取所需的行之前检查字符串中的行数,以避免IndexOutOfRange异常。

Even with regex it's better to use Split method if you are going to split input by some value (but again, it's an overkill if you are simply splitting by lines without some pattern): 即使使用正则表达式,如果要按某个值分割输入,最好还是使用Split方法(但同样,如果仅按行分割而没有某种模式,这也是一个过大的杀伤力):

 var secondLine = Regex.Split(line, Environment.NewLine)[1];

You're trying to match two end of line while the your input only have one. 您正在尝试匹配两个行尾,而您的输入只有一个。

Change to \\n(.*) 更改为\\n(.*)

With the RegexOptions.MultiLine enabled, you can use the following: 启用RegexOptions.MultiLine ,可以使用以下命令:

\n^(.*)$

When Multiline is enabled, ^ and $ will match the beginning and the end of a line instead of the beginning and end of a string. 启用Multiline^$将匹配行的开头和结尾,而不是字符串的开头和结尾。

Example: Regex101 示例: Regex101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM