Parsing text, conditional text

I have a text template with placehoders that I am parsing to replace placeholders with real values.

Text Template:

Name:%name% Age:%age% 

I am using StringBuilder.Replace () to replace placeholders

 sb.Replace("%name%", Person.Name); 

Now I want to make a more advanced algorithm. Some lines of code are conditional. They must be completely removed.

Text template

 Name:%Name% Age:%age% Employer:%employer% 

The line Employer should appear only when using a person (controlled by the logical variable Person.IsEmployed).

UPDATE: I can use open / close tags. How to find text between lines A and B? Can I use Regex? How?

+4
source share
4 answers

Your existing template scheme is not reliable enough - you should add more special placeholders, for example, for example:

 Name:%Name% Age:%age% [if IsEmployed] Employer:%employer% [/if] 

You can parse the [if *] blocks using a regular expression (not tested):

 Match[] ifblocks = Regex.Match(input, "\\[if ([a-zA-Z0-9]+)\\]([^\\[]*)\\[/if\\]"); foreach(Match m in ifblocks) { string originalBlockText = m.Groups[0]; string propertyToCheck = m.Groups[1]; string templateString = m.Groups[2]; // check the property that corresponds to the keyword, ie "IsEmployed" // if it true, do the normal replacement on the templateString // and then replace the originalBlockText with the "filled" templateString // else, just don't write anything out } 

True, although this implementation is full of holes ... Perhaps you will be better off working with template templates, like another answer.

+1
source

Perhaps you could include the "Employer:" label in the replacement text instead of the template:

Template:

 Name:%Name% Age:%age% %employer% 

Replacement

 sb.Replace("%employer%", string.IsNullOrEmpty(Person.Employer) ? "" : "Employer: " + Person.Employer) 
+4
source

Another alternative would be to use a template engine such as Spark or NVelocity .

See a quick example for Spark here.

A complete template engine should give you maximum control over the formatted output. For example, conditional and repeating sections.

+2
source

One option is to make your entire replacement as you are doing now, and then fix the empty variables with the RegEx replacement at the door exit. Something like that:

 Response.Write(RegEx.Replace(sb.ToString(), "\r\n[^:]+:r\n", "\r\n")); 
+1
source

Source: https://habr.com/ru/post/1303380/


All Articles