Reputation: 837
I have a series of strings that I need to de-tokenize. The strings come from a database and look something like this
Subject: Ticket ##TicketID## Created
ShortText: Ticket ##TicketName## created (ID: ##TicketID##).
LongText: <a href="##BaseUrl##/Ticket/Details/##TicketID##">##TicketName##</a> was created on ##CreatedOn##.
Each token is a property name of the associated event object, fired based on some action. For example a TicketCreatedEvent object might look like
public class TicketCreatedEvent : ILAMPEvent {
public Guid TicketID { get; set; }
public string TicketName { get; set; }
public DateTime CreatedOn { get; set; }
public string BaseUrl { get; set; }
}
I was able to find/figure things out as far as dynamically creating a dictionary based on the object, mapping property name to value. I was also able to make some progress on the Regex.Replace call. Replacing the tokens in the Subject string works great using:
Regex.Replace(templates.Subject, @"##(.*)##", match => map[match.Groups[1].Value]);
However, it's not working so great on the ShortText or LongText. From what I can tell from the exception that is getting thrown, Regex is matching too much. Instead of matching
##TicketName##
from the string, it's trying to match
##TicketName## created (ID: ##TicketID##
Obviously I want to match on each of those tokens individually. I assume this is an error on my part, but what am I missing?
Upvotes: 2
Views: 107
Reputation: 336128
.*
is greedy and matches as much as it can, including intervening ##
s.
You have three options:
@"##(.*?)##"
. Works the same, but now .*?
will match as few characters as possible. This should be OK for most cases.#
s in-between ##
s: @"##([^#]*)##"
. However, that means ##hello#there##
would not match.##
s between ##
s: @"##((?:(?!##).)*)##"
. This allows ##hello#there##
. This is probably overkill for the current application, but it will help in more complicated situations, for example when dealing with nested structures.Use whichever one of these conveys your intent most clearly.
Upvotes: 9