Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text parsing, conditional text

I have a text template with placehoders that I parse in order to replace placeholders with real values.

Text Template:

Name:%name%
Age:%age%

I use StringBuilder.Replace() to replace placeholders

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

Now I want to make more advanced algorithm. Some lines of code are conditional. They have to be either removed completely of kept.

Text Template

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

The line Employer should appear only when person is employed (controlled by boolean variable Person.IsEmployed).

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

like image 847
Captain Comic Avatar asked Feb 28 '23 10:02

Captain Comic


2 Answers

Perhaps you could include the label "Employer:" 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)
like image 161
Fredrik Mörk Avatar answered Mar 03 '23 07:03

Fredrik Mörk


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

See a quick example for Spark here

A full-fledged template engine should give you the most control over the formatted output. For example conditionals and repeating sections.

like image 42
Philip Fourie Avatar answered Mar 03 '23 05:03

Philip Fourie