Solved

Regex:  Replace and parse code within custom tags

Posted on 2007-11-16
15
704 Views
Last Modified: 2013-11-07
I have a number of long strings in a database that are interspersed with custom tags example:
texttexttexttext[%im 111023%]... text text text[%im 111010%]text text text.

i need some code that will give me the ability to build a string that looks like:
texttexttext <img src="EVALUATEDCODE(111023)" /> text text <img src="EVALUATEDCODE(111010)" />text text text
0
Comment
Question by:DidiahProd
  • 6
  • 5
  • 2
  • +1
15 Comments
 
LVL 47

Expert Comment

by:Wayne Taylor (webtubbs)
Comment Utility
Hi DidiahProd,

Try this...

        Dim InputString As String = "texttexttexttext[%im 111023%]... text text text[%im 111010%]text text text."
        Dim rx As New System.Text.RegularExpressions.Regex("(\[%im)(.*?)(%\])")
        MsgBox(rx.Replace(InputString, "<img src=""EVALUATEDCODE$2"" />"))

Regards,

Wayne
0
 
LVL 47

Expert Comment

by:Wayne Taylor (webtubbs)
Comment Utility
Actually, this is probably more like it....
        Dim InputString As String = "texttexttexttext[%im 111023%]... text text text[%im 111010%]text text text."
        Dim rx As New System.Text.RegularExpressions.Regex("(\[%im )(.*?)(%\])")
        MsgBox(rx.Replace(InputString, "<img src=""EVALUATEDCODE($2)"" />"))

Open in new window

0
 
LVL 27

Expert Comment

by:ddrudik
Comment Utility
webtubbs has it, but if you want an alternate pattern:
match on:
\[%im\x20(\d+)%\]
replace with:
<img src="EVALUATEDCODE($1)" />
0
 
LVL 6

Expert Comment

by:ventaur
Comment Utility
If you actually want to call some function to generate an image path for the custom tag matches, check out the code below. You would call ParseText and send it your string from the database.

Let me know if you need it in VB instead of C#.
using System.Text.RegularExpressions;

...
 

public string ParseText(string inputText) {

	return Regex.Replace(inputText, @"\[%im (\d+)%\]", new MatchEvaluator(EvaluateTagMatch), RegexOptions.IgnoreCase | RegexOptions.Multiline);

}
 

private string EvaluateTagMatch(Match match) {

	// Get the number (maybe it's an image ID) from the match.

	int ImageId = int.Parse(match.Groups[1].Value);

	

	// Evaluate some code with the number as the parameter to get an image source path.

	string ImagePath = GetImagePath(ImageId);

	

	// Return the custom tag replacement in full.

	return string.Format(@"<img src=""{0}"" />", ImagePath);

}

Open in new window

0
 

Author Comment

by:DidiahProd
Comment Utility
i got webtubbs to work as follows-   is there a benefit to ventaur's solution?  (I do need vb insead of C#).
Thanks!
    Private Function CREval(ByVal strToEval)
 

        Return "HI" & strToEval & "Bye"

    End Function

    Public Function GetMainContent(ByVal mstr As String) As String
 

        Dim rx As New System.Text.RegularExpressions.Regex("(\[%im)(.*?)(%\])")

        Return (rx.Replace(mstr, CREval("$2")))
 

    End Function

Open in new window

0
 
LVL 27

Expert Comment

by:ddrudik
Comment Utility
The one benefit to the pattern that ventaur used (essentially identical to mine) is that is only utilizes one capture group while webtubbs used a pattern that contained three capture groups, two more than required.  Other than that, effectively it will work the same.
0
 

Author Comment

by:DidiahProd
Comment Utility
ventaur, could you post a vb version of that?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 6

Expert Comment

by:ventaur
Comment Utility
I must have misunderstood your use with "EVALUATEDCODE"; thus, the implementation using a match evaluator. But, yes the pattern is the same as ddrudik's and he should get credit if the rest of your code works.

Otherwise, here's the VB of mine using the match evaluator.
Imports System.Text.RegularExpressions

...

 

Public ParseText(inputText As String) As String

    Return Regex.Replace(inputText, "\[%im (\d+)%\]", new MatchEvaluator(EvaluateTagMatch), RegexOptions.IgnoreCase Or RegexOptions.Multiline)

End Function

 

Private EvaluateTagMatch(match As Match) As String

    ' Get the number (maybe it's an image ID) from the match.

    Dim ImageId As Integer = Integer.Parse(match.Groups[1].Value)
 

    ' Evaluate some code with the number as the parameter to get an image source path.

    Dim ImagePath As String = GetImagePath(ImageId)
 

    ' Return the custom tag replacement in full.

    Return String.Format("<img src=""{0}"" />", ImagePath)

End Function

Open in new window

0
 

Author Comment

by:DidiahProd
Comment Utility
Thanks! Looks like we're on the right track.

This code doesn't seem to work, however. I get the error "Error      37      'System.Text.RegularExpressions.MatchEvaluator' is a delegate type and requires a single 'addressof' expression as the only argument to the constructor.      D:\inetpub\vhosts\jhcr\dev\SitePage.aspx.vb      10      78      D:\...\dev\
0
 
LVL 6

Expert Comment

by:ventaur
Comment Utility
Sorry about that. I converted without the IDE.
Public ParseText(inputText As String) As String

    Return Regex.Replace(inputText, "\[%im (\d+)%\]", new MatchEvaluator(AddressOf(EvaluateTagMatch)), RegexOptions.IgnoreCase Or RegexOptions.Multiline)

End Function

Open in new window

0
 

Author Comment

by:DidiahProd
Comment Utility
hmmm- we're close!

now i get this error
Compiler Error Message: BC30455: Argument not specified for parameter 'match' of 'Private Function EvaluateTagMatch(match As System.Text.RegularExpressions.Match) As String'.

    Private Function EvaluateTagMatch(ByVal match As Match) As String

        ' Get the number (maybe it's an image ID) from the match.

        Dim ImageId As Integer = Integer.Parse(match.Groups(1).Value)
 

        ' Evaluate some code with the number as the parameter to get an image source path.

        Dim ImagePath As String = ImageId.ToString
 

        ' Return the custom tag replacement in full.

        Return String.Format("<img src=""{0}"" />", ImagePath)

    End Function
 
 

    Public Function GetMainContent(ByVal inputText As String) As String
 

        Return Regex.Replace(inputText, "\[%show (\d+)%\]", New MatchEvaluator(AddressOf (EvaluateTagMatch())), RegexOptions.IgnoreCase Or RegexOptions.Multiline)

end function

Open in new window

0
 
LVL 6

Expert Comment

by:ventaur
Comment Utility
Make sure you do not use parentheses after "EvaluateTagMatch" or you'll end up actually calling that function instead of passing the address of it to the match evaluator.
Return Regex.Replace(inputText, "\[%show (\d+)%\]", New MatchEvaluator(AddressOf (EvaluateTagMatch)), RegexOptions.IgnoreCase Or RegexOptions.Multiline)

Open in new window

0
 

Author Comment

by:DidiahProd
Comment Utility
I'm sorry i'm not following-  EvaluateTagMatch requires a match as a parameter- this function doesn't include one.
i get that as anerror as well

Thanks
JEd
0
 
LVL 6

Accepted Solution

by:
ventaur earned 325 total points
Comment Utility
No, I'm sorry. I'm just not with it today. I finally got to a location that had Visual Studio so I can refresh my memory on VB syntax. The AddressOf statement is not a function, so please use the code below to avoid all errors this time.
Return Regex.Replace(inputText, "\[%show (\d+)%\]", New MatchEvaluator(AddressOf EvaluateTagMatch), RegexOptions.IgnoreCase Or RegexOptions.Multiline)

Open in new window

0
 

Author Closing Comment

by:DidiahProd
Comment Utility
Thanks! vb/csharp can be headache
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now