-1

Could you guys suggest me how to remove some CSS-rule inside the HTML's syle attribute by using regex in C#.

I want only the text-align and the margin rule are allowed. Else is replace by "" ( empty string ).

For example:

<p style="text-align: left; margin: 5px;color: red;"><strike>iiyuyuiy</strike></p>

Will be become like this.

<p style="text-align: left; margin: 5px;"><strike>iiyuyuiy</strike></p>

The color:red; removed.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
user2877989
  • 587
  • 1
  • 6
  • 19

2 Answers2

1

If you are famiiar with jQuery try .css():

JQuery

$('selctor').css("color", ""); //passing value as null.

Pure JS

document.querySelector('#selctor').style.color= '';
Community
  • 1
  • 1
super
  • 2,288
  • 2
  • 21
  • 23
0

As you probably know, parsing html with regex is fraught with danger. Someone is sure to offer you a Dom parser solution, so this answer is mainly to discuss the regex aspects of things.

I usually like to offer a regex solution anyhow, but the task you propose to undertake is truly an appalling one for regex (though no one is blaming you for this). Why?

Semi-colon are not a perfect delimiter of CSS rules

To match and remove rules, you need to know where they stop. For CSS rule, that is semi-colons. But if a CSS rule has a semi-colon aside from the terminating one, the regex will fail. I don't have an example in mind but it's a frequent point of discussion.

In a world without troublesome semi-colons...

If you had your back against the wall and if semi-colons were not a problem, here is one approach that would work in C#, thanks to its infinite-width lookbehind.

(?<=style="[^"]*)(?:(?:text-align|margin)[^";]*;|(\b[^";]*;)) 

In the replace delegate, using this regex, we would replace the match with an empty string only when capture Group 1 is set.

This time I won't offer sample code as I want to encourage anyone from doing this. Nevertheless, if you were interested in the technique for study purposes, I highly recommend you read this question about matching patterns except in certain contexts.

Community
  • 1
  • 1
zx81
  • 41,100
  • 9
  • 89
  • 105