Regex.Replace not replacing the whole string instead replacing chars in string - c#

My code is as follow:
ArticleContent = Regex.Replace(_article.Article, "[QUOTE]", "<p class='quote'><span style='font-size:1.8em !important;'>" + _article.NewFields.Quotes + "</span></p>", RegexOptions.IgnoreCase);
The problem i'm facing here is, the Regex is not replacing the whole occurrence of the string '[QUOTE]'. Instead it is searching for the letters q,u,o,t,e and replacing them with the replace string. I know the issue is because of the square brackets, but i want that to be replaced as well. Please help.

You must escape square brackets! And don't forget REGEXP are case sensitive. Here's my correction to your code:
ArticleContent = Regex.Replace(_article.Article, "\[quote\]", "<p class='quote'><span style='font-size:1.8em !important;'>" + _article.NewFields.Quotes + "</span></p>", RegexOptions.IgnoreCase);
By the way, I don't see any accourrence of 'quote' enclosed in brackets, so I'm not sure I got what you're trying to do...

Use an non capturing group to replace all the occurrences of the string QUOTE with your desired string ,
(?:QUOTE)
So your code should be,
ArticleContent = Regex.Replace(_article.Article, "(?:QUOTE)", "<p class='quote'><span style='font-size:1.8em !important;'>" + _article.NewFields.Quotes + "</span></p>", RegexOptions.IgnoreCase);
OR
Try to escape the square brackets, if you want to replace [QUOTE] with some-other string becuase suare brackets in regex have a special meaning.
\[QUOTE\]
And your code should be,
ArticleContent = Regex.Replace(_article.Article, "\[QUOTE\]", "<p class='quote'><span style='font-size:1.8em !important;'>" + _article.NewFields.Quotes + "</span></p>", RegexOptions.IgnoreCase);

Related

Regex to insert space C#

I have some string. I need a regex that will replace each occurrence of symbol that is not space + '<' with the same symbol + space + '<'.
In other words if there is '<' without ' ' before it it must add the space.
I've tried something like :
string pattern = "[^ ]<";
string replacement = "$0" + "<";
string result = Regex.Replace(html, pattern, replacement);
Obviously not working as I want.
string pattern = "([^ ])<";
string replacement = "$1" + " <";
You can try something like this.

Regex.Replace to replace sub-string in a string

I am trying to replace ValueBinding="metasys-value:111,813? in following string
Canvas.Top="494" Width="75" Height="75" jcge:RubberBand.ID="ce4f76db-9efc-4b5d-b48b-b62f727d53ef" ValueBinding="meta-value:111,813?analogCommand=37&enumCommand=37" AlarmBinding="meta-item:Alarm%20-%20Present%20Value" TrendBinding="meta-item:Trend%20-%20Present%20Value" SecondaryValueBinding="meta-value:222,813?analogCommand=10&enumCommand=44" SecondaryTrendBinding="meta-item:Trend%20-%20Present%20Value" SensorType="Bulb"
by new string by using
patch = Regex.Replace(patch, "ValueBinding=" + "\".*,813", "ValueBinding=" + "\"" + primaryObjectReference + ",813");
but it replace string till second ,813 occurrence. how can I replace only ValueBinding="metasys-value:111,813? with new value
Use [^\"]* or .*? instead of .* and add \b to the start of the regex.
\b matches a word boundary, eg. the space before ValueBinding.
[^\"]* will match all characters except ", .*? will match everything non greedily.
In your case:
patch = Regex.Replace(patch, "\\bValueBinding=" + "\".*?,813", "ValueBinding=" + "\"" + primaryObjectReference + ",813");
This sounds logic because in you expression you have ".,813", which will much 111,813 and 222,813 as well. If i have understand it well, you must replace ".,813" with ".*111,813\?".

Using Regex Replace instead of String Replace

I am not clued up on Regex as much as I should be, so this may seem like a silly question.
I am splitting a string into a string[] with .Split(' ').
The purpose is to check the words, or replace any.
The problem I'm having now, is that for the word to be replaces, it has to be an exact match, but with the way I'm splitting it, there might be a ( or [ with the split word.
So far, to counter that, I'm using something like this:
formattedText.Replace(">", "> ").Replace("<", " <").Split(' ').
This works fine for now, but I want to incorporate more special chars, such as [;\\/:*?\"<>|&'].
Is there a quicker way than the method of my replacing, such as Regex? I have a feeling my route is far from the best answer.
EDIT
This is an (example) string
would be replaced to
This is an ( example ) string
If you want to replace whole words, you can do that with a regular expression like this.
string text = "This is an example (example) noexample";
string newText = Regex.Replace(text, #"\bexample\b", "!foo!");
newText will contain "This an !foo! (!foo!) noexample"
The key here is that the \b is the word break metacharacter. So it will match at the beginning or end of a line, and the transitions between word characters (\w) and non-word characters (\W). The biggest difference between it and using \w or \W is that those won't match at the beginning or end of lines.
I thing this is the right thing you want
if you want these -> ;\/:*?"<>|&' symbols to replace
string input = "(exam;\\/:*?\"<>|&'ple)";
Regex reg = new Regex("[;\\/:*?\"<>|&']");
string result = reg.Replace(input, delegate(Match m)
{
return " " + m.Value + " ";
});
if you want to replace all characters except a-zA-Z0-9_
string input = "(example)";
Regex reg = new Regex(#"\W");
string result = reg.Replace(input, delegate(Match m)
{
return " " + m.Value + " ";
});

C# Regex replace in string only outside tags

I have a string, which represents part of xml.
string text ="word foo<tag foo='a' />another word "
and I need to replace particular words in this string. So I used this code:
Regex regex = new Regex("\\b" + co + "\\b", RegexOptions.IgnoreCase);
return regex.Replace(text, new MatchEvaluator(subZvyrazniStr));
static string subZvyrazniStr(Match m)
{
return "<FtxFraze>" + m.ToString() + "</FtxFraze>";
}
But the problem of my code is, that it also replaces string inside tags, which i don't want to. So what should I add, to replace words only outside tags?
Ex.: when I set variable co to "foo" I want to return "word <FtxFraze>foo</FtxFraze><tag foo='a' />another word"
Thanks
A simple trick like this may suffice in some cases if you are not that picky:
\bfoo\b(?![^<>]*>)
This is what you want
(?<!\<[\w\s]*?)\bfoo\b(?![\w\s]*?>)
works here
I had answered a related question here
Try this regex:
Regex r = new Regex(#"\b" + rep + #".*?(?=\<)\b", RegexOptions.IgnoreCase);

Replace text in string with delimeters using Regex

I have a string something like,
string str = "(50%silicon +20%!(20%Gold + 80%Silver)| + 30%Alumnium)";
I need a Regular Expression which would Replace the contents in between ! and | with an empty string. The result should be (50%silicon +20% + 30%Alumnium).
If the string contains something like (with nested delimiters):
string str = "(50%silicon +20%!(80%Gold + 80%Silver + 20%!(20%Iron + 80%Silver)|)|
+ 30%Alumnium)";
The result should be (50%silicon +20% + 30%Alumnium) - ignoring the nested delimiters.
I've tried the following Regex, but it doesn't ignore the nesting:
Regex.Replace(str , #"!.+?\|", "", RegexOptions.IgnoreCase);
You are using the lazy quantifier +? which will look for the smallest possible substring that matches your regex. To get the result you are looking for, you want to use the greedy quantifier + which will match the largest substring possible.
The following regex (not tested in C# because I don't have it available, but this should work for any standard regex implementation) will do what you want:
'!.+\|'
using System.Text.RegularExpressions;
str = Regex.Replace(str , #"!.+?\|", "", RegexOptions.IgnoreCase);
Regex.Replace(str, #"!.+?\||\)\|", "", RegexOptions.IgnoreCase);
Works for both provided strings. I extended the regex with a 2nd check on ")/" to replace the leftover characters.

Categories