Skip to main content
 首页 » 编程设计

c#之正则表达式帮助之匹配任意数量的字符

2024年01月13日35exmyth

我在文本文件中有以下类型的字符串集:

<< /ImageType 1 
/Width 986 /Height 1 
/BitsPerComponent 8 
/Decode [0 1 0 1 0 1] 
/ImageMatrix [986 0 0 -1 0 1] 
/DataSource < 
803fe0503824160d0784426150b864361d0f8844625138a4562d178c466351b8e4763d1f904864523924964d27944a6552b964b65d2f984c665339a4d66d379c4e6753b9e4f67d3fa05068543a25168d47a4526954ba648202 
> /LZWDecode filter >> image } def 

上面定义了 100 多个图像。

我需要找到文档中定义的所有此类图像。
这是我的代码-

string txtFile = @"text file path"; 
string fileContents = File.ReadAllText(txtFile); 
 
string pattern = @"<< /ImageType 1.*(\n|\r|\r\n)*image } def"; //match any number of characters between `<< /ImageType 1` and `image } def` 
MatchCollection matchCollection = Regex.Matches(fileContents, pattern, RegexOptions.Singleline); 
int count = matchCollection.Count; // returns 1 

但是,我只得到一个匹配 - 而定义了大约 600 个图像。
但由于模式中使用了“换行”字符,它们似乎都匹配在一起。

任何人都可以指导我需要什么来修改正则表达式匹配的正确结果为 600。

请您参考如下方法:

原因是正则表达式通常是贪心的,即匹配总是尽可能长。因此,image } def包含在 .* 中.我认为这里最好的方法是执行两个单独的正则表达式查询,一个用于 << /ImageType 1和一个 image } def .第一个模式的每个匹配项都将恰好对应第二个模式的一个匹配项,并且由于这些匹配项在原始字符串中带有索引,您可以通过访问适当的子字符串来重建图像。