简体   繁体   English

如何在文件内容中匹配正则表达式模式而不循环遍历文件中的每一行?

[英]How do I match the regular expression pattern within the content of a file without looping through each line in the file?

Im searching for a pattern within a file. 我在文件中搜索模式。 This pattern is not limited to a single line. 该模式不限于单行。 It spreads over more than one line, ie more than one line group together to contain this pattern. 它分布在多于一条线上,即,多于一个线组一起包含了该模式。 Hence, it's not possible to loop through line-by-line in the file and check whether the pattern exists or not. 因此,不可能在文件中逐行循环并检查模式是否存在。 The pattern is given below: 模式如下:

/public.+\\s+(\\w+)\\([^\\)]*\\)\\s*.+?return\\s*\\w+?\\.GetQuestion\\s*\\(/g

Can anyone please tell the C# coding how to match the pattern with in the file ? 谁能告诉C#编码如何与文件中的模式匹配?

I suspect you need to read the whole file (using ReadToEnd , as suggested by RandomNoob) but then also specify RegexOptions.Singleline to put it into Singleline mode : 我怀疑您需要读取整个文件(使用ReadToEnd ,如ReadToEnd所建议),然后还要指定RegexOptions.Singleline使其进入Singleline模式

The RegexOptions.Singleline option, or the s inline option, causes the regular expression engine to treat the input string as if it consists of a single line. RegexOptions.Singleline选项或s inline选项使正则表达式引擎将输入字符串视为由单行组成。 It does this by changing the behavior of the period (.) language element so that it matches every character, instead of matching every character except for the newline character \\n or \ . 它通过更改句点(。)语言元素的行为来做到这一点,以使其匹配每个字符,而不是匹配除换行符\\ n或\\ u000A之外的每个字符。

Regex pattern = new Regex(
    @"public.+\s+(\w+)\([^\)]*\)\s*.+?return\s*\w+?\.GetQuestion\s*\(",
    RegexOptions.Singleline);

使用StreamReader ReadToEnd与之匹配吗?

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

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