开发者

c# regex replace

开发者 https://www.devze.com 2023-01-09 12:06 出处:网络
I have a database containing Page ojects with html content. A lot of the rows in the db contain this content

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();

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 pl开发者_运维问答ease.

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 ;)


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>";

(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)

And it should work.

[EDIT] Oh, and fixing the replace method:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号