Working With Multiple Rules

Learn how to combine multiple rules in a single Transformer, control rule precedence (LIFO), share settings with DefaultRuleSet, and decide between cascading rules and multi-pass pipelines.

Product: 

Class: 

Warning

uCalc API Preview Release Notice:The uCalc engine has successfully transitioned to modern cross-platform environments.The next phase envolves some structural changes, performance optimizations, and API refinements.The API is subject to breaking changes prior to the stable release. Please evaluate the preview version thoroughly before production use.

Remarks

In earlier topics, we defined one rule at a time. In real-world tasks—like refactoring code, converting markup, or building a DSL—a single Transformer typically holds many rules working together.

Rather than running one find-and-replace across our entire text and then starting over for the next rule, the uCalc Transformer evaluates your rules concurrently in a single, token-aware pass. Understanding how multiple rules interact is the key to building clean, powerful, and predictable transformations.


1. Concurrent Matching (One Pass, Many Rules)

When you add multiple FromTo(), Pattern(), and SkipOver() rules to the same Transformer, uCalc walks the token stream from left to right and checks all active rules at each position:

  1. Text Position Priority: Whichever rule matches earliest in the input text wins first.
  2. Boundary Protection: By default, while a variable capture like {text} is scanning forward, it stays aware of other active rules and respects their boundaries instead of blindly swallowing them.
  3. Exclusion First: Any SkipOver() rule acts as a protected "dead zone," preventing other rules from matching inside excluded blocks (such as comments or code sections).

2. Rule Order Matters: LIFO Precedence

What happens if two rules can match starting at the exact same position in the text?

uCalc resolves ties using LIFO (Last-In, First-Out) precedence: the most recently defined rule is checked first.

  • Define general (catch-all) rules first.
  • Define specific (more restrictive) rules last so they take priority.

For example, when converting Markdown-style emphasis:

  • *{text}* (general) must be defined before **{text}** (specific).
  • If the italic rule were defined last, it would greedily match the first * of **bold** and produce broken markup.
  • Because the bold rule is defined last, uCalc checks for **...** first. If that pattern fails to complete, uCalc automatically backtracks and tries the next most recently defined rule sharing that anchor (*...*).

3. Managing Settings Across Many Rules

When a Transformer grows to dozens of rules, configuring each rule individually gets repetitive. uCalc gives you two layers of control:

  • Shared Defaults (DefaultRuleSet): Configure DefaultRuleSet before adding your rules to establish shared behavior—such as CaseSensitive, WhitespaceSensitive, StatementSensitive, or RewindOnChange. Every new rule inherits those settings as its starting template.
  • Per-Rule Overrides & Toggles: Each FromTo() or Pattern() call returns a Rule object. You can override defaults on a single rule (e.g., making just one rule case-sensitive), disable it at runtime with rule.Active = false, or tag it with rule.Tag and rule.Description for debugging.

4. When One Rule's Output Feeds Another: % vs RewindOnChange vs. Pass()

By default, once a rule replaces a chunk of text, the Transformer moves past the replacement and continues forward. When you want rules to interact with each other's output, choose between these distinct mechanisms:

MechanismHow It WorksBest Used For
Immediate Transform %Immediately transforms any nested matches found within the captured text, feeding the transformed version of the text to the variable capture, before moving on to the next part of the transformation.Can be used to transform text before turning it into quoted text.
RewindOnChange = trueImmediately re-scans the newly replaced text using the same rule set.Recursive or nested transformations (e.g., converting a list item line, then re-scanning inside it for **bold** text).
Pass()Runs rules in separate, sequential stages where the output of Pass 0 becomes the input of Pass 1.Multi-phase pipelines where rules shouldn't compete (e.g., Pass 1 normalizes syntax, Pass 2 formats or extracts values).

Tip: If you need a secondary set of rules to run only inside the text captured by a specific parent rule (such as parsing elements inside an HTML <nav> tag), see Hierarchical Parsing (LocalTransformer). To inspect step-by-step how multiple rules modify your text, use TraceTransform().


💡 Why uCalc? (Comparative Analysis)

With standard Regular Expressions, applying multiple rules usually means chaining separate Regex.Replace() calls in a loop:

AspectChained Regex.Replace() CallsuCalc Multi-Rule Transformer
ExecutionScans the entire string from scratch for every rule; earlier replacements can accidentally trigger later rules.Evaluates all rules concurrently in a single token-aware pass, with explicit opt-in for re-scanning (RewindOnChange) or staging (Pass()).
ConflictsRequires complex negative lookarounds to stop general patterns from colliding with specific ones or comments.Handled cleanly via LIFO precedence, automatic backtracking, and declarative SkipOver() dead zones.
MaintainabilityGlobal flags (/i, /s) apply to a whole pattern; toggling rules requires custom if branching in host code.Mix case-sensitive and case-insensitive rules in one Transformer, share templates via DefaultRuleSet, and toggle rules dynamically with .Active.

Examples

Demonstrates multiple rules running together in one Transformer—defining the general rule before the specific rule (LIFO) while protecting raw blocks with SkipOver

ID: 1483

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// 1. General rule defined first (lower priority)
t.FromTo("*{text}*", "<i>{text}</i>");

// 2. Specific rule defined last (higher priority - LIFO)
t.FromTo("**{text}**", "<b>{text}</b>");

// 3. Dead zone: ignore anything inside [raw]...[/raw]
t.SkipOver("<raw>{content}</raw>");

t.Text = "Use **bold**, *italic*, and <raw>*literal*</raw> text.";
Console.WriteLine(t.Transform());
				
			
Use <b>bold</b>, <i>italic</i>, and <raw>*literal*</raw> text.
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();

   // 1. General rule defined first (lower priority)
   t.FromTo("*{text}*", "<i>{text}</i>");

   // 2. Specific rule defined last (higher priority - LIFO)
   t.FromTo("**{text}**", "<b>{text}</b>");

   // 3. Dead zone: ignore anything inside [raw]...[/raw]
   t.SkipOver("<raw>{content}</raw>");

   t.Text("Use **bold**, *italic*, and <raw>*literal*</raw> text.");
   cout << t.Transform() << endl;
}
				
			
Use <b>bold</b>, <i>italic</i>, and <raw>*literal*</raw> text.
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      
      '// 1. General rule defined first (lower priority)
      t.FromTo("*{text}*", "<i>{text}</i>")
      
      '// 2. Specific rule defined last (higher priority - LIFO)
      t.FromTo("**{text}**", "<b>{text}</b>")
      
      '// 3. Dead zone: ignore anything inside [raw]...[/raw]
      t.SkipOver("<raw>{content}</raw>")
      
      t.Text = "Use **bold**, *italic*, and <raw>*literal*</raw> text."
      Console.WriteLine(t.Transform())
   End Sub
End Module
				
			
Use <b>bold</b>, <i>italic</i>, and <raw>*literal*</raw> text.
RewindOnChange

ID: 152

				
					using uCalcSoftware;

var uc = new uCalc();
var ExprT = uc.ExpressionTransformer;  // Transformer used for Eval() and Evaluate()

ExprT.DefaultRuleSet.RewindOnChange = true;

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
Console.WriteLine($"Input: {Expression}");
Console.WriteLine($"Transform: {ExprT.Transform(Expression)}");
Console.WriteLine($"Eval: {uc.Eval(Expression)}");
				
			
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto ExprT = uc.ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

   ExprT.DefaultRuleSet().RewindOnChange(true);

   ExprT.FromTo("AddUp({x})", "{x}");
   ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

   ExprT.FromTo("ArgCount({x})", "1");
   ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

   ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

   auto Expression = "Average(1, 2, 3, 4)";
   cout << "Input: " << Expression << endl;
   cout << "Transform: " << ExprT.Transform(Expression) << endl;
   cout << "Eval: " << uc.Eval(Expression) << endl;
}
				
			
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim ExprT = uc.ExpressionTransformer  '// Transformer used for Eval() and Evaluate()
      
      ExprT.DefaultRuleSet.RewindOnChange = true
      
      ExprT.FromTo("AddUp({x})", "{x}")
      ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))")
      
      ExprT.FromTo("ArgCount({x})", "1")
      ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))")
      
      ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})")
      
      Dim Expression = "Average(1, 2, 3, 4)"
      Console.WriteLine($"Input: {Expression}")
      Console.WriteLine($"Transform: {ExprT.Transform(Expression)}")
      Console.WriteLine($"Eval: {uc.Eval(Expression)}")
   End Sub
End Module
				
			
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
Matches

ID: 114

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>";
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.Matches) {
   Console.WriteLine(match.Text);
   Console.WriteLine($"Start pos: {match.StartPosition}");
   Console.WriteLine($"End pos: {match.EndPosition}");
   Console.WriteLine($"Length: {match.Length}");
   Console.WriteLine("");
}
				
			
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
   //     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
   //     0         10        20        30        40        50        60        70        80        90
   //     ^             ^                                           ^                ^                  ^
   // Carrets (^) represent starting and ending point of the matches

   t.Pattern("<{tag}>{text}</{tag}>");
   t.Pattern("<b>{text}</b>");
   t.Pattern("<h3>{text}</h3>");
   t.SkipOver("<!--{text}-->");
   t.Find();

   for(auto match : t.Matches()) {
      cout << match.Text() << endl;
      cout << "Start pos: " << match.StartPosition() << endl;
      cout << "End pos: " << match.EndPosition() << endl;
      cout << "Length: " << match.Length() << endl;
      cout << "" << endl;
   }
}
				
			
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Text = "<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>"
      '//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
      '//     0         10        20        30        40        50        60        70        80        90
      '//     ^             ^                                           ^                ^                  ^
      '// Carrets (^) represent starting and ending point of the matches
      
      t.Pattern("<{tag}>{text}</{tag}>")
      t.Pattern("<b>{text}</b>")
      t.Pattern("<h3>{text}</h3>")
      t.SkipOver("<!--{text}-->")
      t.Find()
      
      For Each match In t.Matches
         Console.WriteLine(match.Text)
         Console.WriteLine($"Start pos: {match.StartPosition}")
         Console.WriteLine($"End pos: {match.EndPosition}")
         Console.WriteLine($"Length: {match.Length}")
         Console.WriteLine("")
      Next
   End Sub
End Module
				
			
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
Rule Name

ID: 130

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<b>(5+4)</b> this and that etc";
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
Console.WriteLine("--- Matches ---");
Console.WriteLine(t.Matches.Text);
Console.WriteLine("--- Pattern names ---");
Console.WriteLine(a.Name);
Console.WriteLine(b.Name);
Console.WriteLine(c.Name);
Console.WriteLine(d.Name);
Console.WriteLine("--- Pattern defs ---");
Console.WriteLine(a.Pattern);
Console.WriteLine(b.Pattern);
Console.WriteLine(c.Pattern);
Console.WriteLine(d.Pattern);
				
			
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Text("<b>(5+4)</b> this and that etc");
   auto a = t.Pattern("<{tg}>");
   auto b = t.Pattern("This {body} That");
   auto c = t.Pattern("etc");
   auto d = t.Pattern("({expr})");

   t.Filter();
   cout << "--- Matches ---" << endl;
   cout << t.Matches().Text() << endl;
   cout << "--- Pattern names ---" << endl;
   cout << a.Name() << endl;
   cout << b.Name() << endl;
   cout << c.Name() << endl;
   cout << d.Name() << endl;
   cout << "--- Pattern defs ---" << endl;
   cout << a.Pattern() << endl;
   cout << b.Pattern() << endl;
   cout << c.Pattern() << endl;
   cout << d.Pattern() << endl;
}
				
			
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Text = "<b>(5+4)</b> this and that etc"
      Dim a = t.Pattern("<{tg}>")
      Dim b = t.Pattern("This {body} That")
      Dim c = t.Pattern("etc")
      Dim d = t.Pattern("({expr})")
      
      t.Filter()
      Console.WriteLine("--- Matches ---")
      Console.WriteLine(t.Matches.Text)
      Console.WriteLine("--- Pattern names ---")
      Console.WriteLine(a.Name)
      Console.WriteLine(b.Name)
      Console.WriteLine(c.Name)
      Console.WriteLine(d.Name)
      Console.WriteLine("--- Pattern defs ---")
      Console.WriteLine(a.Pattern)
      Console.WriteLine(b.Pattern)
      Console.WriteLine(c.Pattern)
      Console.WriteLine(d.Pattern)
   End Sub
End Module
				
			
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})