c#正则表达式替换 [英] c# regex replace

查看:71
本文介绍了c#正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含带有 html 内容的页面对象的数据库.db 中的很多行都包含此内容

I have a database containing Page ojects with html content. A lot of the rows in the db contain this content

  <p style="float: left; margin-right: 20px; height: 300px;">
        <img src="...">More html ...
 </p>

所以我创建了一个超级简单的正则表达式替换:

So I created a super simple regex replace:

 foreach (var page in db.Pages)
                {
                    string pattern = @"<p style=""float: left; margin-right: 20px;"">(.*)</p>/ms";
                    if( Regex.Match(page.Content, pattern).Success)
                    {
                        page.Content = Regex.Replace(page.Content, pattern, "<div class=\"contentimage\" >$1</div>");
                    }
                }
//                db.SubmitChanges();

尽管当我在正则表达式测试工具中运行正则表达式时,它仍然有效.但在 c# 代码中它没有.谁能帮帮我.

Altough when I run the regex in a regex testing tool, it works. but in c# code it doesn't. Can anyone help me out please.

如果有人知道如何使用 sql 中的正则表达式替换进行更新,那就没问题了.

If anyone know how to do an update with the regex replace in sql, that would be fine to.

正则表达式不是我的强项(虽然很遗憾).但它在我要尽快学习的清单上;)

Regex isn't my strongest point (altough a great shame). But it is on my list of things to learn asap ;)

推荐答案

您的问题是/ms".您正在尝试指定几个正则表达式标志,但 C# 指定的标志与 php/perl 不同(您的正则表达式测试器可能会测试针对这些语言的正则表达式.我建议 Expresso(它是免费的),用于处理 .NET 正则表达式).将您的模式更改为:

Your problem is "/ms". You're trying to specify a couple of regex flags, but C# specifies flags differently than php/perl (your regex tester probably tests regexes aimed at those languages. I suggest Expresso (it's free) for working with .NET regexes). Change your pattern to this:

string pattern = @"<p style=""float: left; margin-right: 20px; height: 300px;"">(.*)</p>";

(另请注意,我添加了height"属性以使其匹配——这只是一个错字吗?)

(also note that I added the "height" attribute in order to make it match -- was that just a typo?)

以及您对此的正则表达式实例化:

And your regex instantiation to this:

if( Regex.Match(page.Content, pattern,RegexOptions.Multiline | RegexOptions.Singleline).Success)

它应该可以工作.

哦,还有修复替换方法:

Oh, and fixing the replace method:

page.Content = Regex.Replace(page.Content, pattern, "<div class=\"contentimage\" >$1</div>", RegexOptions.Multiline | RegexOptions.Singleline);

这篇关于c#正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆