How to Replace the generic css style into empty string using C# - c#

When i take a list of items from one list, some css styles are added into that. I want to remove / Replace that.
The following code is used to replace the style generic. But it is not given the result.
flag.Text = flag.Text.Replace("style=[\"'](.*)[\"']", "");
But it is not replacing. How to give this. Or shall i use Contains method?

You probably want to try using Regex.Replace (and using Multiline option, just in case) instead of string.Replace:
RegexOptions options = RegexOptions.Multiline;
flag.Text = Regex.Replace(flag.Text, "style=[\"'](.*)[\"']", "", options);
What you show above is Replace using string.Replace. It tries to find exact match of the static text instead of text with pattern. If you want to replace text with pattern, use Regex.Replace instead.

I think you are trying to replace the style by using the string.replace() methode but i think it cant do a regex like replace. I think you need to take a look at Regex.Replace.

Related

How do I remove specific paired tags?

I'm using C# and trying to remove a specific pair of tags from string like
Remove <color=#FFFFFF>White </color>Not <color=#000000>Black</color>
And what I want is
Remove White Not <color=#000000>Black</color>
I tried to do it by myself but failed.Is there a way to do this?Any help would be appreciated!
I'm not sure what exactly you've already tried,
But this can easily be done by doing a Replace with RegularExpressions:
var original = "Remove <color=#FFFFFF>White </color>Not <color=#000000>Black</color>";
var replaced = Regex.Replace(original, "<color=#FFFFFF>(.*?)<\\/color>", "$1");
In the regex pattern, you can see I captured what's within the color tag to preserve the text inside, and then replaced the entire thing with that group capture, essentially removing everything around it.

C# Regular Expression Reversing Match

I am looking to convert a part of a string which is substringof('has',verb) into contains(verb,'has')
As you can see, what is changing is just substring to contains and the two parameters passed to the function reversed.
I am looking for a generic solution, by using regex. Preferably using tags. i.e once i get two matches, i need to be able to reverse the matches by using $2$1 (This is how i remember doing this in perl)
You can use this regular expression code:
var re = new Regex(#"substringof\('([^']+)',([^)]+)\)");
string output = re.Replace(input, #"contains($2, '$1')");
.NET Fiddle example
You can use a regex like this:
.*?\((.*?),(.*?)\)
Working demo
Then you can use a string replacement like this:
contains(\2,\1) or
contains($2,$1)
Btw, if you just want to change the substringof, then you can use:
substringof\((.*?),(.*?)\)

C# Regex.replace Pattern needed

Usually I make my Regex patterns by myself, but I can't figure this one out:
I need a Regex.Replace that replaces "'Number'/'Number'" to "'Number'von'Number'".
Example: "2/5" schould become "2von5".
The problem is that I can't just replace "/" to "von" because there are other "/" that are needed.
You can replace (?<=\d)/(?=\d) with von, using lookaround.
Another option is to replace (\d)/(\d) with $1von$2 (though that would fail on 1/2/3).

Regex for a string

It would be great if someone could provide me the Regular expression for the following string.
Sample 1: <div>abc</div><br>
Sample 2: <div>abc</div></div></div></div></div><br>
As you can see in the samples provided above, I need to match the string no matter how many number of </div> occurs. If there occurs any other string between </div> and <br>, say like this <div>abc</div></div></div>DEF</div></div><br> OR <div>abc</div></div></div></div></div>DEF<br>, then the Regex should not match.
Thanks in advance.
Try this:
<div>([^<]+)(?:<\/div>)*<br>
As seen on rubular
Notes:
This only works if there are not tags in the abc part (or anything that has a < symbol).
You might want to use start and end of string anchors (^<div>([^<]+)(?:<\/div>)*<br>$ if you want your string to match the pattern exactly.
If you want to allow the abc part to be empty, use * instead of +
That being said, you should be wary of using regex to parse HTML.
In this example, you can use regex because you are parsing a (hopefully) known, regular subset of HTML. But a more robust solution (ie: an [X]HTML parser like HtmlAgilityPack) is preferred when it comes to parsing HTML.
You need to use a real parser. Things like infinitely nested tags can't be handled via regex.
You could also include a named group in the the expression, e.g.:
<div>(?<text>[^<]*)(?:<\/div>)*<br>
Implemented in C#:
var regex = new Regex(#"<div>(?<text>[^<]*)(?:<\/div>)*<br>");
Func<Match, string> getGroupText = m => (m.Success && m.Groups["text"] != null) ? m.Groups["text"].Value : null;
Func<string, string> getText = s => getGroupText(regex.Match(s));
Console.WriteLine(getText("<div>abc</div><br>"));
Console.WriteLine(getText("<div>123</div></div></div></div></div><br>"));
NullUserException's answer is good. Here are a couple of questions, and variations, depending on what you want.
Do you want to prevent anything from occurring before the open div tag? If so, keep the ^ at the beginning of the regex. If not, drop it.
The rest of this post refers to the following section of the regex:
([^<]+?)
Do you want to capture the contents of the div, or just know that it matches your form? To capture, leave it as is. If you don't need to capture, drop the parentheses from the above.
Do you want to match if there is nothing inside the div? If so change the + in the above to *
Finally, although it will work fine, you don't need the ? in the above.
I think, this regex is more flexible:
<div\b[^><]*+>(?>.*?</div>)(?:\s*+</div>)*+\s*+<br(?:\s*+/)?>
I don't include the ^ and $ in the beginning and the end of my regex because we cannot assure that your sample will always in a single line.

Text parsing, conditional text

I have a text template with placehoders that I parse in order to replace placeholders
with real values.
Text Template:
Name:%name%
Age:%age%
I use StringBuilder.Replace() to replace placeholders
sb.Replace("%name%", Person.Name);
Now I want to make more advanced algorithm. Some lines of code are conditional. They
have to be either removed completely of kept.
Text Template
Name:%Name%
Age:%age%
Employer:%employer%
The line Employer should appear only when person is employed (controlled by boolean variable Person.IsEmployed).
UPDATE: I could use open/close tags. How can find text between string A and B?
Can I use Regex? How?
Perhaps you could include the label "Employer:" in the replacement text instead of the template:
Template:
Name:%Name%
Age:%age%
%employer%
Replacement
sb.Replace("%employer%",
string.IsNullOrEmpty(Person.Employer) ? "" : "Employer: " + Person.Employer)
Another alternative might be to use a template engine such as Spark or NVelocity.
See a quick example for Spark here
A full-fledged template engine should give you the most control over the formatted output. For example conditionals and repeating sections.
Your current templating scheme isn't robust enough - you should add more special placeholders, like this for example:
Name:%Name%
Age:%age%
[if IsEmployed]
Employer:%employer%
[/if]
You can parse out [if *] blocks using a regex (not tested):
Match[] ifblocks = Regex.Match(input, "\\[if ([a-zA-Z0-9]+)\\]([^\\[]*)\\[/if\\]");
foreach(Match m in ifblocks) {
string originalBlockText = m.Groups[0];
string propertyToCheck = m.Groups[1];
string templateString = m.Groups[2];
// check the property that corresponds to the keyword, i.e. "IsEmployed"
// if it's true, do the normal replacement on the templateString
// and then replace the originalBlockText with the "filled" templateString
// else, just don't write anything out
}
Really, though, this implementation is full of holes... You may be better off with a templating framework like another answer suggested.
One option would be to do all of your replacement as you're doing now, then fix empty variables with a RegEx replacement on the way out the door. Something like this:
Response.Write(RegEx.Replace(sb.ToString(), "\r\n[^:]+:r\n", "\r\n"));

Categories

Resources