Skip to main content
 首页 » 编程设计

c#之如何在不循环遍历文件中的每一行的情况下匹配文件内容中的正则表达式模式

2024年02月03日30daizhj

我正在文件中搜索模式。此模式不限于单行。它分布在多条线上,即多条线组合在一起以包含此模式。因此,不可能逐行遍历文件并检查模式是否存在。模式如下:

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

谁能告诉 C# 编码如何匹配文件中的模式?

请您参考如下方法:

我怀疑您需要读取整个文件(使用 ReadToEnd,如 RandomNoob 所建议的那样),但随后还要指定 RegexOptions.Singleline把它放进Singleline mode :

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. 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 \u000A.

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