uCalc SDK Interactive Examples

A practical example of parsing a value from a simple key-value pair in a configuration string.

ID: 1273

				
					using uCalcSoftware;

var uc = new uCalc();
using (var s = new uCalc.String("User: admin; Role: user; Department: Sales;")) {
   
   // Extract the text between 'Department: ' and the trailing semicolon
   var department = s.Between("Department: ", ";");

   Console.WriteLine($"Department is '{department}'");
}
				
			
Department is ' Sales'
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::String s("User: admin; Role: user; Department: Sales;");
      s.Owned(); // Causes s to be released when it goes out of scope

      // Extract the text between 'Department: ' and the trailing semicolon
      auto department = s.Between("Department: ", ";");

      cout << "Department is '" << department << "'" << endl;
   }
}
				
			
Department is ' Sales'
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using s As New uCalc.String("User: admin; Role: user; Department: Sales;")
         
         '// Extract the text between 'Department: ' and the trailing semicolon
         Dim department = s.Between("Department: ", ";")
         
         Console.WriteLine($"Department is '{department}'")
      End Using
   End Sub
End Module
				
			
Department is ' Sales'
A practical example of parsing names with an optional middle name, using a positive conditional block.

ID: 792

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Pattern: Capture first, optional middle, and last names.
// Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
"User: {last}, {first}{middle: {middle}}");

Console.WriteLine(t.Transform("Name: John Doe"));
Console.WriteLine(t.Transform("Name: John Quincy Adams"));
				
			
User: Doe, John
User: Adams, John Quincy
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   // Pattern: Capture first, optional middle, and last names.
   // Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
   t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
   "User: {last}, {first}{middle: {middle}}");

   cout << t.Transform("Name: John Doe") << endl;
   cout << t.Transform("Name: John Quincy Adams") << endl;
}
				
			
User: Doe, John
User: Adams, John Quincy
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      '// Pattern: Capture first, optional middle, and last names.
      '// Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
      t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
      "User: {last}, {first}{middle: {middle}}")
      
      Console.WriteLine(t.Transform("Name: John Doe"))
      Console.WriteLine(t.Transform("Name: John Quincy Adams"))
   End Sub
End Module
				
			
User: Doe, John
User: Adams, John Quincy
A practical example of retrieving an expression's parent uCalc instance to dynamically add a formatting rule before evaluation.

ID: 605

				
					using uCalcSoftware;

var uc = new uCalc();
// Practical (Real World)
// Parse an expression
var myExpr = uc.Parse("5 + 4");
Console.WriteLine($"Initial evaluation: {myExpr.Evaluate()}");

// Retrieve the parent uCalc instance from the expression object
var parentUc = myExpr.uCalc;

// Use the parent instance to add a new formatting rule
parentUc.Format("Result = 'Answer = ' + Result");

// The new format is now active for this expression's context
Console.WriteLine($"Formatted evaluation: {myExpr.EvaluateStr()}");
				
			
Initial evaluation: 9
Formatted evaluation: Answer = 9
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Practical (Real World)
   // Parse an expression
   auto myExpr = uc.Parse("5 + 4");
   cout << "Initial evaluation: " << myExpr.Evaluate() << endl;

   // Retrieve the parent uCalc instance from the expression object
   auto parentUc = myExpr.uCalc();

   // Use the parent instance to add a new formatting rule
   parentUc.Format("Result = 'Answer = ' + Result");

   // The new format is now active for this expression's context
   cout << "Formatted evaluation: " << myExpr.EvaluateStr() << endl;
}
				
			
Initial evaluation: 9
Formatted evaluation: Answer = 9
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Practical (Real World)
      '// Parse an expression
      Dim myExpr = uc.Parse("5 + 4")
      Console.WriteLine($"Initial evaluation: {myExpr.Evaluate()}")
      
      '// Retrieve the parent uCalc instance from the expression object
      Dim parentUc = myExpr.uCalc
      
      '// Use the parent instance to add a new formatting rule
      parentUc.Format("Result = 'Answer = ' + Result")
      
      '// The new format is now active for this expression's context
      Console.WriteLine($"Formatted evaluation: {myExpr.EvaluateStr()}")
   End Sub
End Module
				
			
Initial evaluation: 9
Formatted evaluation: Answer = 9
A practical example parsing multiple command variations for different intents, such as playing music and setting alarms.

ID: 1455

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.DefaultRuleSet.CaseSensitive = false;

// Define multiple rules for different intents
t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}");
t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}");

Console.WriteLine(t.Transform("play music by Queen"));
Console.WriteLine(t.Transform("play the song Bohemian Rhapsody"));
Console.WriteLine(t.Transform("set an alarm for 7 am"));
				
			
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   t.DefaultRuleSet().CaseSensitive(false);

   // Define multiple rules for different intents
   t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
   t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}");
   t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}");

   cout << t.Transform("play music by Queen") << endl;
   cout << t.Transform("play the song Bohemian Rhapsody") << endl;
   cout << t.Transform("set an alarm for 7 am") << endl;
}
				
			
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      t.DefaultRuleSet.CaseSensitive = false
      
      '// Define multiple rules for different intents
      t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}")
      t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}")
      t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}")
      
      Console.WriteLine(t.Transform("play music by Queen"))
      Console.WriteLine(t.Transform("play the song Bohemian Rhapsody"))
      Console.WriteLine(t.Transform("set an alarm for 7 am"))
   End Sub
End Module
				
			
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

ID: 1142

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");

// Transform the input in one go and print the result
t.Text = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";
Console.WriteLine($"Sanitized: '{t.Transform()}'");
				
			
Sanitized: ' Welcome! Please enjoy. '
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   // Rule 1: Remove script tags and their content (case-insensitive, multi-line)
   t.FromTo("<script>{content}</script>", "");
   t.DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

   // Rule 2: Normalize one or more whitespace characters to a single space
   t.FromTo("{@Whitespace:ws}", " ");

   // Transform the input in one go and print the result
   t.Text("  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ");
   cout << "Sanitized: '" << t.Transform() << "'" << endl;
}
				
			
Sanitized: ' Welcome! Please enjoy. '
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      '// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
      t.FromTo("<script>{content}</script>", "")
      t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false)
      
      '// Rule 2: Normalize one or more whitespace characters to a single space
      t.FromTo("{@Whitespace:ws}", " ")
      
      '// Transform the input in one go and print the result
      t.Text = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  "
      Console.WriteLine($"Sanitized: '{t.Transform()}'")
   End Sub
End Module
				
			
Sanitized: ' Welcome! Please enjoy. '
A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

ID: 1145

				
					using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Rule 1: Remove script tags and their content (case-insensitive, multi-line)
   t.FromTo("<script>{content}</script>", "");
   t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false);

   // Rule 2: Normalize one or more whitespace characters to a single space
   t.FromTo("{@Whitespace:ws}", " ");

   string userInput = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";

   // Transform the input in one go and print the result
   Console.WriteLine($"Sanitized: '{t.Transform(userInput)}'");
}
				
			
Sanitized: ' Welcome! Please enjoy. '
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::Transformer t;
      t.Owned(); // Causes t to be released when it goes out of scope
      // Rule 1: Remove script tags and their content (case-insensitive, multi-line)
      t.FromTo("<script>{content}</script>", "");
      t.DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

      // Rule 2: Normalize one or more whitespace characters to a single space
      t.FromTo("{@Whitespace:ws}", " ");

      string userInput = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";

      // Transform the input in one go and print the result
      cout << "Sanitized: '" << t.Transform(userInput) << "'" << endl;
   }
}
				
			
Sanitized: ' Welcome! Please enjoy. '
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using t As New uCalc.Transformer()
         '// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
         t.FromTo("<script>{content}</script>", "")
         t.DefaultRuleSet.SetCaseSensitive(false).SetStatementSensitive(false)
         
         '// Rule 2: Normalize one or more whitespace characters to a single space
         t.FromTo("{@Whitespace:ws}", " ")
         
         Dim userInput As String = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  "
         
         '// Transform the input in one go and print the result
         Console.WriteLine($"Sanitized: '{t.Transform(userInput)}'")
      End Using
   End Sub
End Module
				
			
Sanitized: ' Welcome! Please enjoy. '
A practical example showing how to inspect multiple items and display their type properties, distinguishing between simple and compound types.

ID: 617

				
					using uCalcSoftware;

var uc = new uCalc();
var x = uc.DefineVariable("x = 10.5"); // double
var y = uc.DefineVariable("y = 'hello'"); // string
var z = uc.DefineVariable("z As Complex = 1+2*#i"); // complex

Console.WriteLine($"Item: {x.Name}, Type: {x.DataType.Name}, Compound: {x.DataType.IsCompound}");
Console.WriteLine($"Item: {y.Name}, Type: {y.DataType.Name}, Compound: {y.DataType.IsCompound}");
Console.WriteLine($"Item: {z.Name}, Type: {z.DataType.Name}, Compound: {z.DataType.IsCompound}");
				
			
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

#define tf(IsTrue) ((IsTrue) ? "True" : "False")

int main() {
   uCalc uc;
   auto x = uc.DefineVariable("x = 10.5"); // double
   auto y = uc.DefineVariable("y = 'hello'"); // string
   auto z = uc.DefineVariable("z As Complex = 1+2*#i"); // complex

   cout << "Item: " << x.Name() << ", Type: " << x.DataType().Name() << ", Compound: " << tf(x.DataType().IsCompound()) << endl;
   cout << "Item: " << y.Name() << ", Type: " << y.DataType().Name() << ", Compound: " << tf(y.DataType().IsCompound()) << endl;
   cout << "Item: " << z.Name() << ", Type: " << z.DataType().Name() << ", Compound: " << tf(z.DataType().IsCompound()) << endl;
}
				
			
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim x = uc.DefineVariable("x = 10.5") '// double
      Dim y = uc.DefineVariable("y = 'hello'") '// string
      Dim z = uc.DefineVariable("z As Complex = 1+2*#i") '// complex
      
      Console.WriteLine($"Item: {x.Name}, Type: {x.DataType.Name}, Compound: {x.DataType.IsCompound}")
      Console.WriteLine($"Item: {y.Name}, Type: {y.DataType.Name}, Compound: {y.DataType.IsCompound}")
      Console.WriteLine($"Item: {z.Name}, Type: {z.DataType.Name}, Compound: {z.DataType.IsCompound}")
   End Sub
End Module
				
			
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True
A practical example showing how to iterate through all matches and print the name of the rule that generated each one for debugging.

ID: 952

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "Log: INFO, Data: 123, Log: WARN";

// Define two rules with different starting anchors
t.Pattern("Log: {@Alpha}");
t.Pattern("Data: {@Number}");
t.Find();

Console.WriteLine("--- Match Analysis ---");
foreach(var match in t.Matches) {
   Console.WriteLine($"Match '{match.Text}' was found by rule '{match.Rule.Name}'");
}
				
			
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   t.Text("Log: INFO, Data: 123, Log: WARN");

   // Define two rules with different starting anchors
   t.Pattern("Log: {@Alpha}");
   t.Pattern("Data: {@Number}");
   t.Find();

   cout << "--- Match Analysis ---" << endl;
   for(auto match : t.Matches()) {
      cout << "Match '" << match.Text() << "' was found by rule '" << match.Rule().Name() << "'" << endl;
   }
}
				
			
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      t.Text = "Log: INFO, Data: 123, Log: WARN"
      
      '// Define two rules with different starting anchors
      t.Pattern("Log: {@Alpha}")
      t.Pattern("Data: {@Number}")
      t.Find()
      
      Console.WriteLine("--- Match Analysis ---")
      For Each match In t.Matches
         Console.WriteLine($"Match '{match.Text}' was found by rule '{match.Rule.Name}'")
      Next
   End Sub
End Module
				
			
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
A practical example showing how to manage two separate uCalc instances with conflicting variable names.

ID: 681

				
					using uCalcSoftware;

var uc = new uCalc();
// Create two independent uCalc instances
var uc1 = new uCalc();
var uc2 = new uCalc();

// Define a variable 'x' in each instance with a different value
var itemX1 = uc1.DefineVariable("x = 100");
var itemX2 = uc2.DefineVariable("x = 200");

// Use the item to get its parent context and evaluate 'x * 2'
// This correctly uses uc1's context where x is 100.
Console.WriteLine($"Context 1: {itemX1.uCalc.Eval("x * 2")}");

// This correctly uses uc2's context where x is 200.
Console.WriteLine($"Context 2: {itemX2.uCalc.Eval("x * 2")}");

// Clean up the instances
uc1.Release();
uc2.Release();
				
			
Context 1: 200
Context 2: 400
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Create two independent uCalc instances
   uCalc uc1;
   uCalc uc2;

   // Define a variable 'x' in each instance with a different value
   auto itemX1 = uc1.DefineVariable("x = 100");
   auto itemX2 = uc2.DefineVariable("x = 200");

   // Use the item to get its parent context and evaluate 'x * 2'
   // This correctly uses uc1's context where x is 100.
   cout << "Context 1: " << itemX1.uCalc().Eval("x * 2") << endl;

   // This correctly uses uc2's context where x is 200.
   cout << "Context 2: " << itemX2.uCalc().Eval("x * 2") << endl;

   // Clean up the instances
   uc1.Release();
   uc2.Release();
}
				
			
Context 1: 200
Context 2: 400
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Create two independent uCalc instances
      Dim uc1 As New uCalc()
      Dim uc2 As New uCalc()
      
      '// Define a variable 'x' in each instance with a different value
      Dim itemX1 = uc1.DefineVariable("x = 100")
      Dim itemX2 = uc2.DefineVariable("x = 200")
      
      '// Use the item to get its parent context and evaluate 'x * 2'
      '// This correctly uses uc1's context where x is 100.
      Console.WriteLine($"Context 1: {itemX1.uCalc.Eval("x * 2")}")
      
      '// This correctly uses uc2's context where x is 200.
      Console.WriteLine($"Context 2: {itemX2.uCalc.Eval("x * 2")}")
      
      '// Clean up the instances
      uc1.Release()
      uc2.Release()
   End Sub
End Module
				
			
Context 1: 200
Context 2: 400
A practical example showing how to remap a match found in a substring back to the global coordinates of the original document.

ID: 850

				
					using uCalcSoftware;

var uc = new uCalc();
string document = "HEADER::BEGIN[data to find]END::FOOTER";

// 1. Isolate the content block we want to search in.
// Assume the block we care about is between BEGIN and END.
var startIndex = document.IndexOf("BEGIN[") + 6;
var endIndex = document.IndexOf("]END");
var contentLength = endIndex - startIndex;
var contentBlock = document.Substring(startIndex, contentLength);
Console.WriteLine($"Searching within substring: '{contentBlock}'");

// 2. Perform a find operation on just that substring.
var t = uc.NewTransformer().SetText(contentBlock);
t.Pattern("find");
t.Find();
var matches = t.Matches;

Console.WriteLine($"Local match StartPosition: {matches[0].StartPosition}"); // Relative to 'contentBlock'

// 3. Apply the offset to remap to the global 'document' coordinate space.
matches.ApplyOffset(startIndex);

Console.WriteLine($"Global match StartPosition: {matches[0].StartPosition}");
				
			
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   string document = "HEADER::BEGIN[data to find]END::FOOTER";

   // 1. Isolate the content block we want to search in.
   // Assume the block we care about is between BEGIN and END.
   auto startIndex = document.find("BEGIN[") + 6;
   auto endIndex = document.find("]END");
   auto contentLength = endIndex - startIndex;
   auto contentBlock = document.substr(startIndex, contentLength);
   cout << "Searching within substring: '" << contentBlock << "'" << endl;

   // 2. Perform a find operation on just that substring.
   auto t = uc.NewTransformer().SetText(contentBlock);
   t.Pattern("find");
   t.Find();
   auto matches = t.Matches();

   cout << "Local match StartPosition: " << matches[0].StartPosition() << endl; // Relative to 'contentBlock'

   // 3. Apply the offset to remap to the global 'document' coordinate space.
   matches.ApplyOffset(startIndex);

   cout << "Global match StartPosition: " << matches[0].StartPosition() << endl;
}
				
			
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim Document As String = "HEADER::BEGIN[data to find]END::FOOTER"
      
      '// 1. Isolate the content block we want to search in.
      '// Assume the block we care about is between BEGIN and END.
      Dim startIndex = document.IndexOf("BEGIN[") + 6
      Dim endIndex = document.IndexOf("]END")
      Dim contentLength = endIndex - startIndex
      Dim contentBlock = document.Substring(startIndex, contentLength)
      Console.WriteLine($"Searching within substring: '{contentBlock}'")
      
      '// 2. Perform a find operation on just that substring.
      Dim t = uc.NewTransformer().SetText(contentBlock)
      t.Pattern("find")
      t.Find()
      Dim matches = t.Matches
      
      Console.WriteLine($"Local match StartPosition: {matches(0).StartPosition}") '// Relative to 'contentBlock'
      
      '// 3. Apply the offset to remap to the global 'document' coordinate space.
      matches.ApplyOffset(startIndex)
      
      Console.WriteLine($"Global match StartPosition: {matches(0).StartPosition}")
   End Sub
End Module
				
			
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
A practical example showing the difference between counting all matches and counting matches for a specific rule.

ID: 786

See: Count
				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>");

// Define rules for different tags
var h1Rule = t.Pattern("<h1>{text}</h1>");
var pRule = t.Pattern("<p>{text}</p>");
t.Find();

// Get the total count of all matches from all rules
Console.WriteLine($"Total matches (all rules): {t.Matches.Count()}");

// Get the count for only the paragraph rule
Console.WriteLine($"Paragraph matches only: {pRule.Matches.Count()}");
				
			
Total matches (all rules): 3
Paragraph matches only: 2
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>");

   // Define rules for different tags
   auto h1Rule = t.Pattern("<h1>{text}</h1>");
   auto pRule = t.Pattern("<p>{text}</p>");
   t.Find();

   // Get the total count of all matches from all rules
   cout << "Total matches (all rules): " << t.Matches().Count() << endl;

   // Get the count for only the paragraph rule
   cout << "Paragraph matches only: " << pRule.Matches().Count() << endl;
}
				
			
Total matches (all rules): 3
Paragraph matches only: 2
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>")
      
      '// Define rules for different tags
      Dim h1Rule = t.Pattern("<h1>{text}</h1>")
      Dim pRule = t.Pattern("<p>{text}</p>")
      t.Find()
      
      '// Get the total count of all matches from all rules
      Console.WriteLine($"Total matches (all rules): {t.Matches.Count()}")
      
      '// Get the count for only the paragraph rule
      Console.WriteLine($"Paragraph matches only: {pRule.Matches.Count()}")
   End Sub
End Module
				
			
Total matches (all rules): 3
Paragraph matches only: 2
A practical example simulating a small spreadsheet with interdependent cells.

ID: 1380

				
					using uCalcSoftware;

var uc = new uCalc();
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

Console.WriteLine($"Initial C1: {uc.Eval("C1()")}"); // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

Console.WriteLine($"Updated B1: {uc.Eval("B1()")}"); // Should now be 50 * 2 = 100
Console.WriteLine($"Updated C1: {uc.Eval("C1()")}"); // Should now be 50 + 100 = 150
				
			
Initial C1: 30
Updated B1: 100
Updated C1: 150
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define interdependent 'cells' using the Overwrite command.
   uc.Define("Overwrite ~~ Function: A1() = 10");
   uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
   uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

   cout << "Initial C1: " << uc.Eval("C1()") << endl; // Should be 10 + (10 * 2) = 30

   // Now, overwrite the source cell A1. All dependent cells should automatically update.
   uc.Define("Overwrite ~~ Function: A1() = 50");

   cout << "Updated B1: " << uc.Eval("B1()") << endl; // Should now be 50 * 2 = 100
   cout << "Updated C1: " << uc.Eval("C1()") << endl; // Should now be 50 + 100 = 150
}
				
			
Initial C1: 30
Updated B1: 100
Updated C1: 150
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define interdependent 'cells' using the Overwrite command.
      uc.Define("Overwrite ~~ Function: A1() = 10")
      uc.Define("Overwrite ~~ Function: B1() = A1() * 2")
      uc.Define("Overwrite ~~ Function: C1() = A1() + B1()")
      
      Console.WriteLine($"Initial C1: {uc.Eval("C1()")}") '// Should be 10 + (10 * 2) = 30
      
      '// Now, overwrite the source cell A1. All dependent cells should automatically update.
      uc.Define("Overwrite ~~ Function: A1() = 50")
      
      Console.WriteLine($"Updated B1: {uc.Eval("B1()")}") '// Should now be 50 * 2 = 100
      Console.WriteLine($"Updated C1: {uc.Eval("C1()")}") '// Should now be 50 + 100 = 150
   End Sub
End Module
				
			
Initial C1: 30
Updated B1: 100
Updated C1: 150
A practical example that calculates line-item totals for a list of products by capturing quantity and price.

ID: 1218

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Rule to find quantity and price, then calculate total.
// Note the explicit Double() to convert the captured numerical
// values as text into double-precision numbers for {@Eval}.
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}",
"{@Self}, Total: {@Eval: Double(qty) * Double(price)}");

var invoice = """
Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50
""";

Console.WriteLine(t.Transform(invoice));
				
			
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   // Rule to find quantity and price, then calculate total.
   // Note the explicit Double() to convert the captured numerical
   // values as text into double-precision numbers for {@Eval}.
   t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}",
   "{@Self}, Total: {@Eval: Double(qty) * Double(price)}");

   auto invoice = R"(Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50)";

   cout << t.Transform(invoice) << endl;
}
				
			
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      '// Rule to find quantity and price, then calculate total.
      '// Note the explicit Double() to convert the captured numerical
      '// values as text into double-precision numbers for {@Eval}.
      t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}",
      "{@Self}, Total: {@Eval: Double(qty) * Double(price)}")
      
      Dim invoice = "Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50"
      
      Console.WriteLine(t.Transform(invoice))
   End Sub
End Module
				
			
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
A practical example that extracts all `<a>` tags, but only from within a specific `<nav>` section of an HTML document.

ID: 1240

				
					using uCalcSoftware;

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

// Ignore multi-line formatting
t.DefaultRuleSet.StatementSensitive = false;

// 1. Parent rule captures the content of the <nav> block.
var navRule = t.Pattern("<nav>{content}</nav>");

// 2. Get the local transformer for the nav block.
var local_t = navRule.LocalTransformer;

// 3. This rule will only find `<a>` tags inside the <nav> block.
local_t.Pattern("<a href={url}>{text}</a>");

var html = """
<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/other">other link</a>.</p>
</main>
""";

t.Text = html;
t.Find();

Console.WriteLine("--- Found Links (Innermost Matches Only) ---");
// Use InnermostOnly to see only the results from the local transformer.
Console.WriteLine(t.GetMatches(MatchesOption.InnermostOnly).Text);
				
			
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

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

   // Ignore multi-line formatting
   t.DefaultRuleSet().StatementSensitive(false);

   // 1. Parent rule captures the content of the <nav> block.
   auto navRule = t.Pattern("<nav>{content}</nav>");

   // 2. Get the local transformer for the nav block.
   auto local_t = navRule.LocalTransformer();

   // 3. This rule will only find `<a>` tags inside the <nav> block.
   local_t.Pattern("<a href={url}>{text}</a>");

   auto html = R"(<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/other">other link</a>.</p>
</main>)";

   t.Text(html);
   t.Find();

   cout << "--- Found Links (Innermost Matches Only) ---" << endl;
   // Use InnermostOnly to see only the results from the local transformer.
   cout << t.GetMatches(MatchesOption::InnermostOnly).Text() << endl;
}
				
			
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      
      '// Ignore multi-line formatting
      t.DefaultRuleSet.StatementSensitive = false
      
      '// 1. Parent rule captures the content of the <nav> block.
      Dim navRule = t.Pattern("<nav>{content}</nav>")
      
      '// 2. Get the local transformer for the nav block.
      Dim local_t = navRule.LocalTransformer
      
      '// 3. This rule will only find `<a>` tags inside the <nav> block.
      local_t.Pattern("<a href={url}>{text}</a>")
      
      Dim html = "<nav>
  <a href=""/home"">Home</a>
  <a href=""/about"">About</a>
</nav>
<main>
  <p>Some text with another <a href=""/other"">other link</a>.</p>
</main>"
      
      t.Text = html
      t.Find()
      
      Console.WriteLine("--- Found Links (Innermost Matches Only) ---")
      '// Use InnermostOnly to see only the results from the local transformer.
      Console.WriteLine(t.GetMatches(MatchesOption.InnermostOnly).Text)
   End Sub
End Module
				
			
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
A practical example that finds all HTML-style tags and prints the text of each one.

ID: 833

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "<h1>Title</h1><p>Text</p>";

// Pattern to find any tag and its content
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var allMatches = t.Matches;
Console.WriteLine($"Found {allMatches.Count()} matches:");

// Loop through each Match object and print its Text
foreach(var match in allMatches) {
   Console.WriteLine($" - {match.Text}");
}
				
			
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Text("<h1>Title</h1><p>Text</p>");

   // Pattern to find any tag and its content
   t.Pattern("<{tag}>{content}</{tag}>");
   t.Find();

   auto allMatches = t.Matches();
   cout << "Found " << allMatches.Count() << " matches:" << endl;

   // Loop through each Match object and print its Text
   for(auto match : allMatches) {
      cout << " - " << match.Text() << endl;
   }
}
				
			
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Text = "<h1>Title</h1><p>Text</p>"
      
      '// Pattern to find any tag and its content
      t.Pattern("<{tag}>{content}</{tag}>")
      t.Find()
      
      Dim allMatches = t.Matches
      Console.WriteLine($"Found {allMatches.Count()} matches:")
      
      '// Loop through each Match object and print its Text
      For Each match In allMatches
         Console.WriteLine($" - {match.Text}")
      Next
   End Sub
End Module
				
			
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
A practical example that iterates through all words in a sentence to find the one with the greatest length.

ID: 824

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "Find the longest word in this sentence.";
t.Pattern("{@Alpha}"); // Match all words
t.Find();

int maxLength = 0;
string longestWord = "";
foreach(var match in t.Matches) {
   if (match.Length > maxLength) {
      maxLength = match.Length;
      longestWord = match.Text;
   }
}

Console.WriteLine($"Longest word is '{longestWord}' with length: {maxLength}");
				
			
Longest word is 'sentence' with length: 8
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Text("Find the longest word in this sentence.");
   t.Pattern("{@Alpha}"); // Match all words
   t.Find();

   int maxLength = 0;
   string longestWord = "";
   for(auto match : t.Matches()) {
      if (match.Length() > maxLength) {
         maxLength = match.Length();
         longestWord = match.Text();
      }
   }

   cout << "Longest word is '" << longestWord << "' with length: " << maxLength << endl;
}
				
			
Longest word is 'sentence' with length: 8
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Text = "Find the longest word in this sentence."
      t.Pattern("{@Alpha}") '// Match all words
      t.Find()
      
      Dim maxLength As Integer = 0
      Dim longestWord As String = ""
      For Each match In t.Matches
         If match.Length > maxLength Then
            maxLength = match.Length
            longestWord = match.Text
         End If
      Next
      
      Console.WriteLine($"Longest word is '{longestWord}' with length: {maxLength}")
   End Sub
End Module
				
			
Longest word is 'sentence' with length: 8
A practical example that processes a list of tasks but skips the first two high-priority items.

ID: 986

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var taskList = "Task:1 Task:2 Task:3 Task:4 Task:5";
t.Text = taskList;

var taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}");

// Skip the first two tasks in the list
taskRule.StartAfter = 2;

Console.WriteLine(t.Transform());
				
			
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   auto taskList = "Task:1 Task:2 Task:3 Task:4 Task:5";
   t.Text(taskList);

   auto taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}");

   // Skip the first two tasks in the list
   taskRule.StartAfter(2);

   cout << t.Transform() << endl;
}
				
			
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      Dim taskList = "Task:1 Task:2 Task:3 Task:4 Task:5"
      t.Text = taskList
      
      Dim taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}")
      
      '// Skip the first two tasks in the list
      taskRule.StartAfter = 2
      
      Console.WriteLine(t.Transform())
   End Sub
End Module
				
			
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
A practical example that transpiles a multi-line legacy script, including comments, variables, and a conditional statement with a nested action.

ID: 1377

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
// Rules must be defined in an order that allows for proper transformation.

// 1. Comment rule
t.FromTo("REM {comment}", "// {comment}");

// 2. Variable assignment rule
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

// 3. Print statement rule
t.FromTo("PRINT {output}", "console.log({output});");

// 4. IF...THEN rule with RewindOnChange to handle nested statements
var ifRule = t.FromTo("IF {condition} THEN {action}", """
if ({condition}) {
  {action}
}
""");
ifRule.RewindOnChange = true;

// The legacy script to transpile
var legacyScript = """
REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large"
""";

// Run the transformation
Console.WriteLine(t.Transform(legacyScript));
				
			
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   // Rules must be defined in an order that allows for proper transformation.

   // 1. Comment rule
   t.FromTo("REM {comment}", "// {comment}");

   // 2. Variable assignment rule
   t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

   // 3. Print statement rule
   t.FromTo("PRINT {output}", "console.log({output});");

   // 4. IF...THEN rule with RewindOnChange to handle nested statements
   auto ifRule = t.FromTo("IF {condition} THEN {action}", R"(if ({condition}) {
  {action}
})");
   ifRule.RewindOnChange(true);

   // The legacy script to transpile
   auto legacyScript = R"(REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large")";

   // Run the transformation
   cout << t.Transform(legacyScript) << endl;
}
				
			
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      '// Rules must be defined in an order that allows for proper transformation.
      
      '// 1. Comment rule
      t.FromTo("REM {comment}", "// {comment}")
      
      '// 2. Variable assignment rule
      t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};")
      
      '// 3. Print statement rule
      t.FromTo("PRINT {output}", "console.log({output});")
      
      '// 4. IF...THEN rule with RewindOnChange to handle nested statements
      Dim ifRule = t.FromTo("IF {condition} THEN {action}", "if ({condition}) {
  {action}
}")
      ifRule.RewindOnChange = true
      
      '// The legacy script to transpile
      Dim legacyScript = "REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT ""Value is large"""
      
      '// Run the transformation
      Console.WriteLine(t.Transform(legacyScript))
   End Sub
End Module
				
			
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
A practical example that uses a rule's parent context to define and evaluate an expression.

ID: 998

				
					using uCalcSoftware;

var uc = new uCalc();
// The transformer 't' belongs to the main 'uc' instance.
var t = new uCalc.Transformer(uc);

// Define a variable in the transformer's parent context.
t.uCalc.DefineVariable("VarX = 123");

// This rule is created within 't' and will need to access VarX.
var myRule = t.FromTo("x", "{@Eval: VarX}");

// Get the rule's parent uCalc instance...
var parent_uc = myRule.uCalc;

// ...and use it to evaluate an expression to prove we have the right context.
Console.WriteLine($"Value of VarX in parent context: {parent_uc.Eval("VarX")}");

// Now, run the transformation. The {@Eval} in the rule
// correctly finds 'VarX' in its parent uCalc context.
Console.WriteLine(t.Transform("The value is: x"));
				
			
Value of VarX in parent context: 123
The value is: 123
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // The transformer 't' belongs to the main 'uc' instance.
   uCalc::Transformer t(uc);

   // Define a variable in the transformer's parent context.
   t.uCalc().DefineVariable("VarX = 123");

   // This rule is created within 't' and will need to access VarX.
   auto myRule = t.FromTo("x", "{@Eval: VarX}");

   // Get the rule's parent uCalc instance...
   auto parent_uc = myRule.uCalc();

   // ...and use it to evaluate an expression to prove we have the right context.
   cout << "Value of VarX in parent context: " << parent_uc.Eval("VarX") << endl;

   // Now, run the transformation. The {@Eval} in the rule
   // correctly finds 'VarX' in its parent uCalc context.
   cout << t.Transform("The value is: x") << endl;
}
				
			
Value of VarX in parent context: 123
The value is: 123
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// The transformer 't' belongs to the main 'uc' instance.
      Dim t As New uCalc.Transformer(uc)
      
      '// Define a variable in the transformer's parent context.
      t.uCalc.DefineVariable("VarX = 123")
      
      '// This rule is created within 't' and will need to access VarX.
      Dim myRule = t.FromTo("x", "{@Eval: VarX}")
      
      '// Get the rule's parent uCalc instance...
      Dim parent_uc = myRule.uCalc
      
      '// ...and use it to evaluate an expression to prove we have the right context.
      Console.WriteLine($"Value of VarX in parent context: {parent_uc.Eval("VarX")}")
      
      '// Now, run the transformation. The {@Eval} in the rule
      '// correctly finds 'VarX' in its parent uCalc context.
      Console.WriteLine(t.Transform("The value is: x"))
   End Sub
End Module
				
			
Value of VarX in parent context: 123
The value is: 123
A practical example using `MatchesOption::FocusableOnly` to retrieve results only from rules marked as focusable.

ID: 877

See: GetMatches
				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "ID:100, Name:Admin, ID:200";

// Mark 'ID' rules as focusable, but 'Name' rules as secondary.
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get the matches for the 'idRule' specifically, filtered to only focusable results.
var focusableIdMatches = idRule.GetMatches(MatchesOption.FocusableOnly);

Console.WriteLine($"Focusable 'ID' matches found: {focusableIdMatches.Count()}");
Console.WriteLine(focusableIdMatches.Text);
				
			
Focusable 'ID' matches found: 2
ID:100
ID:200
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Text("ID:100, Name:Admin, ID:200");

   // Mark 'ID' rules as focusable, but 'Name' rules as secondary.
   auto idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
   auto nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
   t.Find();

   // Get the matches for the 'idRule' specifically, filtered to only focusable results.
   auto focusableIdMatches = idRule.GetMatches(MatchesOption::FocusableOnly);

   cout << "Focusable 'ID' matches found: " << focusableIdMatches.Count() << endl;
   cout << focusableIdMatches.Text() << endl;
}
				
			
Focusable 'ID' matches found: 2
ID:100
ID:200
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Text = "ID:100, Name:Admin, ID:200"
      
      '// Mark 'ID' rules as focusable, but 'Name' rules as secondary.
      Dim idRule = t.Pattern("ID:{@Number}").SetFocusable(true)
      Dim nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false)
      t.Find()
      
      '// Get the matches for the 'idRule' specifically, filtered to only focusable results.
      Dim focusableIdMatches = idRule.GetMatches(MatchesOption.FocusableOnly)
      
      Console.WriteLine($"Focusable 'ID' matches found: {focusableIdMatches.Count()}")
      Console.WriteLine(focusableIdMatches.Text)
   End Sub
End Module
				
			
Focusable 'ID' matches found: 2
ID:100
ID:200
A practical example using a fallback content block to provide a default status for log entries.

ID: 791

				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Pattern: Match "Log:", an optional level (Warning or Error), and the message.
// Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}");

Console.WriteLine(t.Transform("Log: This is a standard entry"));
Console.WriteLine(t.Transform("Log: Warning A potential issue was found"));
Console.WriteLine(t.Transform("Log: Error System failure detected"));
				
			
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   // Pattern: Match "Log:", an optional level (Warning or Error), and the message.
   // Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
   t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}");

   cout << t.Transform("Log: This is a standard entry") << endl;
   cout << t.Transform("Log: Warning A potential issue was found") << endl;
   cout << t.Transform("Log: Error System failure detected") << endl;
}
				
			
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      '// Pattern: Match "Log:", an optional level (Warning or Error), and the message.
      '// Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
      t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}")
      
      Console.WriteLine(t.Transform("Log: This is a standard entry"))
      Console.WriteLine(t.Transform("Log: Warning A potential issue was found"))
      Console.WriteLine(t.Transform("Log: Error System failure detected"))
   End Sub
End Module
				
			
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
A practical example using an error handler to provide a custom, user-friendly message when an invalid operation occurs.

ID: 407

				
					using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Check if the specific 'FloatInvalid' error was raised
   if (uc.Error.Code == ErrorCode.FloatInvalid) {
      Console.WriteLine("Error: The calculation resulted in an invalid number (e.g., square root of a negative).");
      // Stop further processing
      uc.Error.Response = ErrorHandlerResponse.Abort;
   }
}


// Register the custom error handler
uc.Error.AddHandler(MyErrorHandler);

// Tell uCalc to raise an error instead of returning 'nan'
uc.Error.TrapOnInvalid = true;

// This will now trigger our custom error handler's message
uc.EvalStr("sqrt(-4)");
				
			
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call MyErrorHandler(Handle_uCalc h) {
   auto uc = uCalc(h);
   // Check if the specific 'FloatInvalid' error was raised
   if (uc.Error().Code() == ErrorCode::FloatInvalid) {
      cout << "Error: The calculation resulted in an invalid number (e.g., square root of a negative)." << endl;
      // Stop further processing
      uc.Error().Response(ErrorHandlerResponse::Abort);
   }
}

int main() {
   uCalc uc;
   // Register the custom error handler
   uc.Error().AddHandler(MyErrorHandler);

   // Tell uCalc to raise an error instead of returning 'nan'
   uc.Error().TrapOnInvalid(true);

   // This will now trigger our custom error handler's message
   uc.EvalStr("sqrt(-4)");
}
				
			
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub MyErrorHandler(ByVal h As Handle_uCalc)
      Dim uc As New uCalc(h)
      '// Check if the specific 'FloatInvalid' error was raised
      If uc.Error.Code = ErrorCode.FloatInvalid Then
         Console.WriteLine("Error: The calculation resulted in an invalid number (e.g., square root of a negative).")
         '// Stop further processing
         uc.Error.Response = ErrorHandlerResponse.Abort
      End If
   End Sub
   
   Public Sub Main()
      Dim uc As New uCalc()
      '// Register the custom error handler
      uc.Error.AddHandler(AddressOf MyErrorHandler)
      
      '// Tell uCalc to raise an error instead of returning 'nan'
      uc.Error.TrapOnInvalid = true
      
      '// This will now trigger our custom error handler's message
      uc.EvalStr("sqrt(-4)")
   End Sub
End Module
				
			
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
A practical example using Clone() to create a specialized parser from a base template, demonstrating rule inheritance.

ID: 1055

See: Clone
				
					using uCalcSoftware;

var uc = new uCalc();
// 1. Create a "base" HTML transformer template
var baseHtmlParser = new uCalc.Transformer();
baseHtmlParser.Description = "Base HTML Parser";
// Rule to skip over comments
baseHtmlParser.SkipOver("<!--{body}->");
// Rule to find any tag
baseHtmlParser.Pattern("<{tag}>");
baseHtmlParser.DefaultRuleSet.SetStatementSensitive(false);

// 2. Create a specialized clone to find only image tags
var imageParser = baseHtmlParser.Clone();
imageParser.Description = "Image Tag Finder";
imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG");

string html = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> ";

// The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
Console.WriteLine(imageParser.Transform(html));

imageParser.Release();
baseHtmlParser.Release();
				
			
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // 1. Create a "base" HTML transformer template
   uCalc::Transformer baseHtmlParser;
   baseHtmlParser.Description("Base HTML Parser");
   // Rule to skip over comments
   baseHtmlParser.SkipOver("<!--{body}->");
   // Rule to find any tag
   baseHtmlParser.Pattern("<{tag}>");
   baseHtmlParser.DefaultRuleSet().SetStatementSensitive(false);

   // 2. Create a specialized clone to find only image tags
   auto imageParser = baseHtmlParser.Clone();
   imageParser.Description("Image Tag Finder");
   imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG");

   string html = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> ";

   // The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
   cout << imageParser.Transform(html) << endl;

   imageParser.Release();
   baseHtmlParser.Release();
}
				
			
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// 1. Create a "base" HTML transformer template
      Dim baseHtmlParser As New uCalc.Transformer()
      baseHtmlParser.Description = "Base HTML Parser"
      '// Rule to skip over comments
      baseHtmlParser.SkipOver("<!--{body}->")
      '// Rule to find any tag
      baseHtmlParser.Pattern("<{tag}>")
      baseHtmlParser.DefaultRuleSet.SetStatementSensitive(false)
      
      '// 2. Create a specialized clone to find only image tags
      Dim imageParser = baseHtmlParser.Clone()
      imageParser.Description = "Image Tag Finder"
      imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG")
      
      Dim html As String = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> "
      
      '// The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
      Console.WriteLine(imageParser.Transform(html))
      
      imageParser.Release()
      baseHtmlParser.Release()
   End Sub
End Module
				
			
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
A practical example using multiple concurrent patterns to find and categorize log entries.

ID: 1066

See: Find
				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.Text = logText;

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");

t.Find();

Console.WriteLine($"Total issues found: {t.Matches.Count()}");
Console.WriteLine("--- Error Matches ---");
Console.WriteLine(errorRule.Matches.Text);
Console.WriteLine("--- Warning Matches ---");
Console.WriteLine(warnRule.Matches.Text);
				
			
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   auto logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
   t.Text(logText);

   // Define rules for different log levels
   auto errorRule = t.Pattern("ERROR: {msg}.");
   auto warnRule = t.Pattern("WARN: {msg}.");

   t.Find();

   cout << "Total issues found: " << t.Matches().Count() << endl;
   cout << "--- Error Matches ---" << endl;
   cout << errorRule.Matches().Text() << endl;
   cout << "--- Warning Matches ---" << endl;
   cout << warnRule.Matches().Text() << endl;
}
				
			
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      Dim logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed."
      t.Text = logText
      
      '// Define rules for different log levels
      Dim errorRule = t.Pattern("ERROR: {msg}.")
      Dim warnRule = t.Pattern("WARN: {msg}.")
      
      t.Find()
      
      Console.WriteLine($"Total issues found: {t.Matches.Count()}")
      Console.WriteLine("--- Error Matches ---")
      Console.WriteLine(errorRule.Matches.Text)
      Console.WriteLine("--- Warning Matches ---")
      Console.WriteLine(warnRule.Matches.Text)
   End Sub
End Module
				
			
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
A practical example using tags to build a simple syntax highlighter that categorizes matches.

ID: 995

				
					using uCalcSoftware;

var uc = new uCalc();
// Practical: Basic Syntax Highlighter
var t = new uCalc.Transformer();

// Define categories with integer tags
var TAG_KEYWORD = 1;
var TAG_STRING = 2;
var TAG_COMMENT = 3;

// Define rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);

t.Text = """
for (i=0; i<10; i++) { s = "hello"; // comment }
""";
t.Find();

foreach(var match in t.Matches) {
   var tag = match.Rule.Tag;
   if (tag == TAG_KEYWORD) {
      Console.WriteLine($"TAG_KEYWORD: {match.Text}");
   } else if (tag == TAG_STRING) {
      Console.WriteLine($"TAG_STRING: {match.Text}");
   } else if (tag == TAG_COMMENT) {
      Console.WriteLine($"TAG_COMMENT: {match.Text}");
   }
}
				
			
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Practical: Basic Syntax Highlighter
   uCalc::Transformer t;

   // Define categories with integer tags
   auto TAG_KEYWORD = 1;
   auto TAG_STRING = 2;
   auto TAG_COMMENT = 3;

   // Define rules and tag them
   t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
   t.Pattern("{@String}").SetTag(TAG_STRING);
   t.Pattern("// {text}").SetTag(TAG_COMMENT);

   t.Text(R"(for (i=0; i<10; i++) { s = "hello"; // comment })");
   t.Find();

   for(auto match : t.Matches()) {
      auto tag = match.Rule().Tag();
      if (tag == TAG_KEYWORD) {
         cout << "TAG_KEYWORD: " << match.Text() << endl;
      } else if (tag == TAG_STRING) {
         cout << "TAG_STRING: " << match.Text() << endl;
      } else if (tag == TAG_COMMENT) {
         cout << "TAG_COMMENT: " << match.Text() << endl;
      }
   }
}
				
			
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Practical: Basic Syntax Highlighter
      Dim t As New uCalc.Transformer()
      
      '// Define categories with integer tags
      Dim TAG_KEYWORD = 1
      Dim TAG_STRING = 2
      Dim TAG_COMMENT = 3
      
      '// Define rules and tag them
      t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD)
      t.Pattern("{@String}").SetTag(TAG_STRING)
      t.Pattern("// {text}").SetTag(TAG_COMMENT)
      
      t.Text = "for (i=0; i<10; i++) { s = ""hello""; // comment }"
      t.Find()
      
      For Each match In t.Matches
         Dim tag = match.Rule.Tag
         If tag = TAG_KEYWORD Then
            Console.WriteLine($"TAG_KEYWORD: {match.Text}")
            ElseIf tag = TAG_STRING Then
            Console.WriteLine($"TAG_STRING: {match.Text}")
            ElseIf tag = TAG_COMMENT Then
            Console.WriteLine($"TAG_COMMENT: {match.Text}")
         End If
      Next
   End Sub
End Module
				
			
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
A practical example using the fluent interface of `Set...` methods to configure multiple properties of a rule in a single chained statement.

ID: 1161

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var rule = t.FromTo("A", "B");

// Chain multiple Set... methods for a clean configuration
rule.SetCaseSensitive(true)
.SetWhitespaceSensitive(false)
.SetQuoteSensitive(false);

// Verify the properties were set using their corresponding getters
Console.WriteLine($"Case Sensitive: {rule.CaseSensitive}");
Console.WriteLine($"Whitespace Sensitive: {rule.WhitespaceSensitive}");
Console.WriteLine($"Quote Sensitive: {rule.QuoteSensitive}");
				
			
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

#define tf(IsTrue) ((IsTrue) ? "True" : "False")

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   auto rule = t.FromTo("A", "B");

   // Chain multiple Set... methods for a clean configuration
   rule.SetCaseSensitive(true)
   .SetWhitespaceSensitive(false)
   .SetQuoteSensitive(false);

   // Verify the properties were set using their corresponding getters
   cout << "Case Sensitive: " << tf(rule.CaseSensitive()) << endl;
   cout << "Whitespace Sensitive: " << tf(rule.WhitespaceSensitive()) << endl;
   cout << "Quote Sensitive: " << tf(rule.QuoteSensitive()) << endl;
}
				
			
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      Dim rule = t.FromTo("A", "B")
      
      '// Chain multiple Set... methods for a clean configuration
      rule.SetCaseSensitive(true).SetWhitespaceSensitive(false).SetQuoteSensitive(false)
      
      '// Verify the properties were set using their corresponding getters
      Console.WriteLine($"Case Sensitive: {rule.CaseSensitive}")
      Console.WriteLine($"Whitespace Sensitive: {rule.WhitespaceSensitive}")
      Console.WriteLine($"Quote Sensitive: {rule.QuoteSensitive}")
   End Sub
End Module
				
			
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
A practical example where a 'data' rule is invalidated if it appears too few times, while a 'header' rule is unaffected.

ID: 949

				
					using uCalcSoftware;

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

Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C

""";
t.Text = document;

var dataRule = t.Pattern("Data: {val}");
var headerRule = t.Pattern("Header: {val}");

dataRule.Minimum = 2;
Console.WriteLine("--- Find with Minimum(2) ---");
t.Find();
Console.WriteLine($"Total Matches: {t.Matches.Count()}");
Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}");
Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}");

dataRule.Minimum = 4;
Console.WriteLine("");
Console.WriteLine("--- Find with Minimum(4) ---");
t.Find();
Console.WriteLine($"Total Matches: {t.Matches.Count()}");
Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}");
Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}");
				
			
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   auto document = R"(
Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C
)";
   t.Text(document);

   auto dataRule = t.Pattern("Data: {val}");
   auto headerRule = t.Pattern("Header: {val}");

   dataRule.Minimum(2);
   cout << "--- Find with Minimum(2) ---" << endl;
   t.Find();
   cout << "Total Matches: " << t.Matches().Count() << endl;
   cout << "Data Matches: " << dataRule.Matches().Count() << endl;
   cout << "Header Matches: " << headerRule.Matches().Count() << endl;

   dataRule.Minimum(4);
   cout << "" << endl;
   cout << "--- Find with Minimum(4) ---" << endl;
   t.Find();
   cout << "Total Matches: " << t.Matches().Count() << endl;
   cout << "Data Matches: " << dataRule.Matches().Count() << endl;
   cout << "Header Matches: " << headerRule.Matches().Count() << endl;
}
				
			
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      Dim document = "
Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C
"
      t.Text = document
      
      Dim dataRule = t.Pattern("Data: {val}")
      Dim headerRule = t.Pattern("Header: {val}")
      
      dataRule.Minimum = 2
      Console.WriteLine("--- Find with Minimum(2) ---")
      t.Find()
      Console.WriteLine($"Total Matches: {t.Matches.Count()}")
      Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}")
      Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}")
      
      dataRule.Minimum = 4
      Console.WriteLine("")
      Console.WriteLine("--- Find with Minimum(4) ---")
      t.Find()
      Console.WriteLine($"Total Matches: {t.Matches.Count()}")
      Console.WriteLine($"Data Matches: {dataRule.Matches.Count()}")
      Console.WriteLine($"Header Matches: {headerRule.Matches.Count()}")
   End Sub
End Module
				
			
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
A practical implementation of the code refactoring utility, safely renaming a function while ignoring occurrences in comments and strings.

ID: 1402

				
					using uCalcSoftware;

var uc = new uCalc();
// Simulate user inputs for the tool
var findText = "GetUserData";
var replaceText = "FetchUserProfile";
var sourceCode = """

// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);

""";

using (var refactorTool = new uCalc.Transformer()) {
   // 1. Define rules to ignore comments. These have the highest precedence.
   refactorTool.SkipOver("// {text}");
   refactorTool.SkipOver("/* {text} */");

   // 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
   var rule = refactorTool.FromTo(findText, replaceText);

   // 3. Run the transformation and print the result.
   Console.WriteLine(refactorTool.Transform(sourceCode));
}
				
			

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Simulate user inputs for the tool
   auto findText = "GetUserData";
   auto replaceText = "FetchUserProfile";
   auto sourceCode = R"(
// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);
)";

   {
      uCalc::Transformer refactorTool;
      refactorTool.Owned(); // Causes refactorTool to be released when it goes out of scope
      // 1. Define rules to ignore comments. These have the highest precedence.
      refactorTool.SkipOver("// {text}");
      refactorTool.SkipOver("/* {text} */");

      // 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
      auto rule = refactorTool.FromTo(findText, replaceText);

      // 3. Run the transformation and print the result.
      cout << refactorTool.Transform(sourceCode) << endl;
   }
}
				
			

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Simulate user inputs for the tool
      Dim findText = "GetUserData"
      Dim replaceText = "FetchUserProfile"
      Dim sourceCode = "
// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print(""Calling GetUserData is not recommended."");
    return http.get(""/users/"" + id);
}
var user = GetUserData(123);
"
      
      Using refactorTool As New uCalc.Transformer()
         '// 1. Define rules to ignore comments. These have the highest precedence.
         refactorTool.SkipOver("// {text}")
         refactorTool.SkipOver("/* {text} */")
         
         '// 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
         Dim rule = refactorTool.FromTo(findText, replaceText)
         
         '// 3. Run the transformation and print the result.
         Console.WriteLine(refactorTool.Transform(sourceCode))
      End Using
   End Sub
End Module
				
			

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);
A practical LISP interpreter that handles variadic (multiple arguments) and nested expressions.

ID: 1417

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.DefaultRuleSet.RewindOnChange = true;

// {@@Eval} evaluates the expression obtained by concatinating the captured
// elements {op} for operator, and {a} and {b} for the two numbers.
// These elements are strings and do not need curly braces within {@@Eval}
// :1 tels it to capture one token at a time.
t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");

// If there are more than to numbers, as indicated by {more}, then the first
// two numbers are evaluated and put back into the list.  The operator remains.
t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");

// If a nested expression is present, it is evaluated immediately, by using
// % in {expr%} and the section is reprocessed again with the resulting value
// since .@RewindOnChange(true) was set.
t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}");
t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}");

// --- Test Cases ---
Console.WriteLine("--- Simple Binary ---");
var expr = "(- 100 25)";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");

Console.WriteLine("--- Variadic (Multiple Args) ---");
expr = "(* 2 3 4)";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");

Console.WriteLine("--- Nested Expressions ---");
expr = "(/ 100 (+ 5 5))";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))";
Console.WriteLine($"LISP: {expr}");
Console.WriteLine($"Result: {t.Transform(expr)}");
Console.WriteLine("");
				
			
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

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

   // {@@Eval} evaluates the expression obtained by concatinating the captured
   // elements {op} for operator, and {a} and {b} for the two numbers.
   // These elements are strings and do not need curly braces within {@@Eval}
   // :1 tels it to capture one token at a time.
   t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");

   // If there are more than to numbers, as indicated by {more}, then the first
   // two numbers are evaluated and put back into the list.  The operator remains.
   t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");

   // If a nested expression is present, it is evaluated immediately, by using
   // % in {expr%} and the section is reprocessed again with the resulting value
   // since .@RewindOnChange(true) was set.
   t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}");
   t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}");

   // --- Test Cases ---
   cout << "--- Simple Binary ---" << endl;
   auto expr = "(- 100 25)";
   cout << "LISP: " << expr << endl;
   cout << "Result: " << t.Transform(expr) << endl;
   cout << "" << endl;

   cout << "--- Variadic (Multiple Args) ---" << endl;
   expr = "(* 2 3 4)";
   cout << "LISP: " << expr << endl;
   cout << "Result: " << t.Transform(expr) << endl;
   cout << "" << endl;

   cout << "--- Nested Expressions ---" << endl;
   expr = "(/ 100 (+ 5 5))";
   cout << "LISP: " << expr << endl;
   cout << "Result: " << t.Transform(expr) << endl;
   expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))";
   cout << "LISP: " << expr << endl;
   cout << "Result: " << t.Transform(expr) << endl;
   cout << "" << endl;
}
				
			
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.DefaultRuleSet.RewindOnChange = true
      
      '// {@@Eval} evaluates the expression obtained by concatinating the captured
      '// elements {op} for operator, and {a} and {b} for the two numbers.
      '// These elements are strings and do not need curly braces within {@@Eval}
      '// :1 tels it to capture one token at a time.
      t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}")
      
      '// If there are more than to numbers, as indicated by {more}, then the first
      '// two numbers are evaluated and put back into the list.  The operator remains.
      t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})")
      
      '// If a nested expression is present, it is evaluated immediately, by using
      '// % in {expr%} and the section is reprocessed again with the resulting value
      '// since .@RewindOnChange(true) was set.
      t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}")
      t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}")
      
      '// --- Test Cases ---
      Console.WriteLine("--- Simple Binary ---")
      Dim expr = "(- 100 25)"
      Console.WriteLine($"LISP: {expr}")
      Console.WriteLine($"Result: {t.Transform(expr)}")
      Console.WriteLine("")
      
      Console.WriteLine("--- Variadic (Multiple Args) ---")
      expr = "(* 2 3 4)"
      Console.WriteLine($"LISP: {expr}")
      Console.WriteLine($"Result: {t.Transform(expr)}")
      Console.WriteLine("")
      
      Console.WriteLine("--- Nested Expressions ---")
      expr = "(/ 100 (+ 5 5))"
      Console.WriteLine($"LISP: {expr}")
      Console.WriteLine($"Result: {t.Transform(expr)}")
      expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))"
      Console.WriteLine($"LISP: {expr}")
      Console.WriteLine($"Result: {t.Transform(expr)}")
      Console.WriteLine("")
   End Sub
End Module
				
			
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
A practical, generic `Print` function that can accept any number of arguments of any type and display them in a formatted string.

ID: 1237

				
					using uCalcSoftware;

var uc = new uCalc();

static void PrintGeneric(uCalc.Callback cb) {
   string output = "";
   var i = 0;
   for ( i = 1; i <= cb.ArgCount(); i++) {
      // Get the item and retrieve its value as a string.
      var item = cb.ArgItem(i);
      output = output + item.ValueStr();
      if (i < cb.ArgCount()) {
         output = output + ", ";
      }
   }
   Console.WriteLine(output);
}

// Define a variadic function that accepts any number of arguments ByHandle.
uc.DefineFunction("Print(ByHandle args As AnyType...)", PrintGeneric);

uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)");
				
			
User:, Alice, ID:, 101, Status:, true
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call PrintGeneric(uCalcBase::Callback cb) {
   string output = "";
   auto i = 0;
   for ( i = 1; i <= cb.ArgCount(); i++) {
      // Get the item and retrieve its value as a string.
      auto item = cb.ArgItem(i);
      output = output + item.ValueStr();
      if (i < cb.ArgCount()) {
         output = output + ", ";
      }
   }
   cout << output << endl;
}
int main() {
   uCalc uc;
   // Define a variadic function that accepts any number of arguments ByHandle.
   uc.DefineFunction("Print(ByHandle args As AnyType...)", PrintGeneric);

   uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)");
}
				
			
User:, Alice, ID:, 101, Status:, true
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub PrintGeneric(ByVal cb As uCalc.Callback)
      Dim output As String = ""
      Dim i = 0
      For i  = 1 To cb.ArgCount()
         '// Get the item and retrieve its value as a string.
         Dim item = cb.ArgItem(i)
         output = output + item.ValueStr()
         If i < cb.ArgCount() Then
            output = output + ", "
         End If
      Next
      Console.WriteLine(output)
   End Sub
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define a variadic function that accepts any number of arguments ByHandle.
      uc.DefineFunction("Print(ByHandle args As AnyType...)", AddressOf PrintGeneric)
      
      uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)")
   End Sub
End Module
				
			
User:, Alice, ID:, 101, Status:, true