• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 425
  • Last Modified:

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.
0
tikusbalap
Asked:
tikusbalap
  • 9
  • 5
  • 2
  • +1
1 Solution
 
brendanmeyerCommented:
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.
0
 
ddayx10Commented:
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

0
 
käµfm³d 👽Commented:
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

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
käµfm³d 👽Commented:
Please disregard my post--it will work, but I misread brendanmeyer's code and agree that his is adequate  :)
0
 
tikusbalapAuthor Commented:
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.
0
 
ddayx10Commented:
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]
0
 
käµfm³d 👽Commented:
I partly agree with ddayx10:  your last post has completely confused the requirement. What is it that you *exactly* trying to do?
0
 
tikusbalapAuthor Commented:
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.
0
 
käµfm³d 👽Commented:
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:
0
 
käµfm³d 👽Commented:
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

0
 
tikusbalapAuthor Commented:
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

0
 
käµfm³d 👽Commented:
In your example above, what is the difference between "GetTagArray()" and "SomeFunction()" ?
0
 
tikusbalapAuthor Commented:
@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.

0
 
käµfm³d 👽Commented:
Something like this?
static void Main(string[] args)
{
    string myLabel = "<p>My title text is <b>here</b></p><p>My title <b>is this</b></p><p>My title <b>can go </b>here</p>";

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

    Console.WriteLine(result);
}

static string DoReplace(string input)
{
    System.Text.RegularExpressions.Regex bTags = new System.Text.RegularExpressions.Regex(@"(?i)<b>(.+?)</b>");
    System.Text.RegularExpressions.Regex pTags = new System.Text.RegularExpressions.Regex(@"(?i)<p>(.+?)</p>");
    System.Text.RegularExpressions.MatchCollection matches;
    string result = input;

    matches = bTags.Matches(input);
    
    foreach (System.Text.RegularExpressions.Match match in matches)
    {
        DoSomeProcessing(match.Groups[1].Value);
    }

    matches = pTags.Matches(input);

    foreach (System.Text.RegularExpressions.Match match in matches)
    {
        DoSomeProcessing(match.Groups[1].Value);
    }

    result = bTags.Replace(result, "<sometag>$1</sometag>");
    result = pTags.Replace(result, "<anothertag>$1</anothertag>");

    return result;
}

Open in new window

0
 
käµfm³d 👽Commented:
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).
0
 
tikusbalapAuthor Commented:
Yes. You gave me the direction. Thanks a lot kaufmed.
0
 
käµfm³d 👽Commented:
Cool. Glad we found a solution for you  :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 9
  • 5
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now