Link to home
Start Free TrialLog in
Avatar of tikusbalap
tikusbalapFlag for Indonesia

asked on

How to replace tag inside a string with another tag?

Experts,

I have string with a tag inside.

string myLabel = "
<p>
My title text is <b>here</b>
</p>

";

How to find <b>here</b> and replace it with <sometag>here</sometag>, then find text inside <p>My title text...</p> with <anothertag>My title text...</anothertag>? Tag is case-insensitive.

It's OK to use regular expressions but I will choose which is not. I hear that RegularExpressions is heavy in C#.

Thank you.
Avatar of Brendan M
Brendan M
Flag of Australia image

if your looking for a specific tag to replace each time

using System.Text.RegularExpressions;

//this will look for <b> or </b>and replace it with <sometag> or </sometag>
Regex regexBTag = new Regex("<(/?)b>");
myLabel = regexBTag.Replace(myLabel, "<${1}sometag>");

//this will look for <p> or </p>and replace it with <anothertag> or </anothertag>
Regex regexPTag = new Regex("<(/?)p>");
myLabel = regexPTag.Replace(myLabel, "<${1}anothertag>");

i create my Regex object as static members of my classes eg
class someclass
{
    static Regex regexPTag = new Regex("<(/?)p>");
...
as this will mean that it isn't compiled within Regex every time you use it. but it only is helpful if you are not changing the regular expression.
If someone told you that RegEx is heavy in C# you should know this is somewhat true, but you also need to understand the context. Many, many things you can do in .NET (even things that are common practice on EE) are too heavy-weight for high-traffic website use.

If your website doesn't have thousands of users the "heavy" loses all meaning. Any/All string manipulation in this manner is going to be inefficient use of power. Strings can be heavy things :)
    protected void Page_Load(object sender, EventArgs e)
    {
        string myNewLabel = replaceStuff("span", "div");
    }


    private string replaceStuff(string tag1, string tag2)
    {
        string myLabel = "<p>My title text is <b>here</b></p>";

        myLabel = myLabel.Replace("b", tag1);
        myLabel = myLabel.Replace("p", tag2);

        return myLabel;
    }

Open in new window

Use the following:
string myLabel = @"
<p>
My title text is <b>here</b>
</p>
";

myLabel = System.Text.RegularExpressions.Regex.Replace(myLabel, @"(?s)<(b)>(.+?)</\1>", "<sometag>$2</sometag>");
myLabel = System.Text.RegularExpressions.Regex.Replace(myLabel, @"(?s)<(p)>(.+?)</\1>", "<anothertag>$2</anothertag>");

Open in new window

Please disregard my post--it will work, but I misread brendanmeyer's code and agree that his is adequate  :)
Avatar of tikusbalap

ASKER

But how to get the value inside the tag also? I mean there will be some processing for the value.

For example:

<b>here</b> and replace it with <sometag>here</sometag>. And the word 'here' will be bold inside my app, but changing the tag.

I hope i will get some stuff like:

string[] tagB = {"here", etc..}
string[] tagP = {"My title text is <b>here</b>", "another text", etc }

Thanks.
That is not what you asked for. You asked for:
<b>here</b> and replace it with <sometag>here</sometag>
AND
<p>My title text...</p> with <anothertag>My title text...</anothertag>

If you are going to change the tags, and the text inside them why oh why wouldn't you just replace the entire string? Youre basically asking "How do I change the entire string a piece at a time?"

You really should re-think what you're trying to do and re-phrase your question very carefully. It sounds like there may be more conditions than you are making clear.

I for one am not going to keep re-writing to bad specs that change each time you see what you asked for is not exactly right. [GIGO]
I partly agree with ddayx10:  your last post has completely confused the requirement. What is it that you *exactly* trying to do?
I'm sorry for the confusion.

I'm actually get the answer direction, but i'm wondering how to get the value inside the tag as well.

I was hope there will be an array of string each tag and its value, so I can change the tag and processing the value.

Sorry for my mistake.
So is it your requirement that you want to be able to pass in an array of strings to a function such that the array of strings is the find/replace data? Something like:
Pushed wrong button  :\

Here is the code that was supposed to be attached to last post:
static void Main(string[] args)
{
    string[] tagB = { "<p>My title text is <b>here</b></p>", "b", "sometag" };
    string[] tagP = { "<p>My title text is <b>here</b></p>", "p", "anothertag" };

    Console.WriteLine(DoReplace(tagB));
    Console.WriteLine(DoReplace(tagP));

    Console.ReadKey();
}

static string DoReplace(string[] searchData)
{
    if (searchData.Length < 3) return null;

    string pattern = string.Concat("<(/?)", searchData[1], ">");
    string replace = string.Concat("<$1", searchData[2], ">");
    
    return Regex.Replace(searchData[0], pattern, replace);
}

Open in new window

kaufmed, thanks for the response. Seems I failed to explain the situation again :(

Here the complete problems:

static void Main(string[] args)
{
	string myLabel = "<p>My title text is <b>here</b></p>";

	// result should be "<anothertag>My title text is <sometag>here</sometag></anothertag>";
	string result = DoReplace(myLabel);
}

static string DoReplace(string input)
{
	string result = input;	
	
	string[] tagB = GetTagArray(input); // should be array {"<b>here</b>"}
	string[] tagP = SomeFunction(input); // should be array {"<p>My title text is <b>here</b></p>"}

	foreach(string item in tagB)
	{
		// 1. How to replace the tag? This is my first question but I need the value inside the tag as well
		result = result.Replace("<b>", "<sometag>");
		result = result.Replace("</b>", "</sometag>");
		
		// 2. How GetValueInsideTheTag problem? I need the value inside the <b> tag for additional processing.
		string value = GetValueInsideTheTag(item);
		
		// some processing value here..
	}
	
	return result;
}

Open in new window

In your example above, what is the difference between "GetTagArray()" and "SomeFunction()" ?
@kaufmed
This is what actualy I need somehow:

- GetTagArray: get all tags containing tag <b>.
- SomeFunction: get all tags containing tag <p>.

It is just example, if you could do them in one function. It is good. Do you have an idea?

Thank you.

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In the above, the call to DoSomeProcessing() represents your need to perform some action on the text within the tag--captured using regex grouping constructs (parentheses).
Yes. You gave me the direction. Thanks a lot kaufmed.
Cool. Glad we found a solution for you  :)