我目前在代码中使用正则表达式,以便从富文本文档中获取大字符串。正则表达式查找任何嵌入的图像并将其解析为字节数组,我可以将其转换为LinkedResource。我需要将RTF从应用程序中的RichTextBox转换为有效的HTML文档,然后转换为可以自动发送的MIME编码的消息。
正则表达式的问题是图像的字符串部分很大,因此我觉得正则表达式试图匹配整个字符串中的许多可能性,而实际上,我只需要查看开头和结尾。本节的结尾。下面的正则表达式包含在较大的正则表达式中,作为可选子句,例如someRegexStringA + "|" + imageRegexString + "|" + "someRegexStringB"
。
我该怎么做才能确保对大字符串进行较少的检查,以使我的应用程序在解析大量图像数据时不会冻结?
// The Regex itself
private static string imageRegexString = @"(?<imageCheck>\\pict)" // Look for the opening image tag
+ @"(?:\\picwgoal(?<widthNumber>[0-9]+))" // Read the size of the image's width
+ @"(?:\\pichgoal(?<heightNumber>[0-9]+))" // Read the size of the image's height
+ @"(?:\\pngblip(\r|\n))" // The image is the newline after this portion of the opening tag and information
+ @"(?<imageData>(.|\r|\n)+?)" // Read the bitmap
+ @"(?:}+)"; // Look for closing braces
// The expression is compiled so it doesn't take as much time during runtime
private static Regex myRegularExpression = new Regex(imageRegexString, RegexOptions.Compiled);
// Iterate through each image in the document
foreach(Match image in myRegularExpression.Matches(myDocument))
{
// Read the image height and width
int imageWidth = int.Parse(image.Groups["widthNumber"].Value);
int imageHeight = int.Parse(image.Groups["heightNumber"].Value);
// Process the image
ProcessImageData(image.Groups["imageData"].Value);
}
首先,我模糊地记得有一个带有Rich Text Editor的InfoPath表单,该表单可以导出为HTML-所以您可能要看一下(尽管我们仍然必须分别附加图像)
至于您的模式:这很简单,只有一条可疑行:
(?<imageData>(.|\r|\n)+?)
这有几个潜在的问题:
+?
是懒惰的,长字符串会导致大量回溯,这可能会导致效率低下。.|\r|\n
也似乎效率很低。您可以使用SingleLine修饰符(或inline(?s:...)
)。.
已经匹配\r
。(.|\r|\n)
-这是一个捕获组,与(?:...)
您在其他地方使用的组不同。我怀疑这正在杀死您-在.Net中,每个字符都以Capture
。形式保存在堆栈中。你不要那样为了安全起见,我建议与所有格小组一起这样做:
(?<imageData>(?>[^}]+))
当然,由于其他变化,模式也可能变慢:someRegexStringA
或someRegexStringB
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句