Products Technologies Demo Docs Blog Support Company

RegEx Based Inline Styling in TX Text Control Using JSON Rules

In this article, we demonstrate how to apply inline styling to text in TX Text Control using regular expressions defined in JSON format. This approach allows for dynamic and flexible text formatting based on specific patterns.

RegEx Based Inline Styling in TX Text Control Using JSON Rules

Sometimes, you don't need a complete document template with predefined styles and placeholders. Maybe you have plain text or imported content and want to automatically highlight important parts, such as email addresses, dates, identifiers, or sensitive data.

This sample solves exactly that problem. The idea is simple. Define a set of rules in a JSON file, where each rule contains a regular expression and an associated TX Text Control InlineStyle. Then, scan the document and apply the matching style to each element found.

The result is a lightweight "document formatter" that can be used for reports, audit logs, technical output, and generated documents where consistency matters.

The Concept: Rules → RegEx → InlineStyle

The core of this solution is a JSON file containing an array of rules. At a high level, the flow looks like this:

  1. Load a JSON file that contains a list of inline styles and rules
  2. Create the required TX Text Control InlineStyle objects once
  3. Parse the document paragraph by paragraph
  4. Run each regex against the paragraph text
  5. Select the match in the document and apply the matching InlineStyle

The result is a document that remains fully editable while specific content stands out visually in a controlled manner.

Example: JSON Rules and Styles

Here is an example of a JSON file defining some rules and styles. The rules.json defines two things:

Inline styles, for example:

  • Email (underlined blue)
  • Date (bold blue)
  • SensitiveData (bold red with background)
  • InlineCode (Consolas with a light background)

And rules, where each regex points to an inline style name. For example, this is the email rule:

{
  "name": "Email address",
  "pattern": "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b",
  "inlineStyleName": "Email",
  "priority": 20,
  "startOffset": 0
}

Creating InlineStyles in TX Text Control

Before applying any rules, the formatter verifies that all JSON styles exist in the document. The interesting part of this concept is that: Styles are dynamically created based on the JSON file, which allows for great flexibility.

This is pure TX Text Control logic:

var style = new InlineStyle(def.Name);
ApplyStyleDefinition(style, def);
tx.InlineStyles.Add(style);

Inline styles are lightweight and ideal for formatting elements within a paragraph, such as an email address or date.

Why Paragraph Based Matching Matters

Offset drift is a common issue when applying RegEx matches to formatted documents. Line breaks, paragraph separators, and the internal representation of the document may cause the indices to shift compared to the raw .Text string.

This is why the sample processes the document paragraph by paragraph.

foreach (Paragraph p in tx.Paragraphs)
{
    string pText = p.Text ?? string.Empty;
    ...
}

Each match uses the paragraph start position as a stable base index:

Start: p.Start + m.Index - 1

This keeps selections consistent even in multi paragraph documents.

Applying the InlineStyle to Matches

After a regular expression match is found, the formatter selects the exact text range and applies the style by name.

tx.Selection.Start = h.Start;
tx.Selection.Length = h.Length;
tx.Selection.FormattingStyle = h.StyleName;

This is the key Text Control call: Applying an InlineStyle to a selection using Selection.FormattingStyle.

Running the Formatter: Full Example

In the sample, we load some demo text, run the formatter, and export to PDF. Here is the complete code:

using var tx = new ServerTextControl();
tx.Create();

tx.Text = """
This document contains RegEx styled text samples.

Contact:
Jane Doe (jane.doe@acme.com)
Support: support@contoso.io

Dates:
Invoice date: 2026-01-20
Delivery date: 20.01.2026
US format date: 1/20/2026

Identifiers:
Order #A1B2C3D4E5
Ticket ID ZXCVBN12
Reference REF 99887766

Phone:
US: +1 (704) 555-0182
DE: +49 170 1234567

Banking:
IBAN (compact): DE89370400440532013000
IBAN (spaced):  DE89 3704 0044 0532 0130 00
Routing number: 021000021
Account number: 123456789012

Sensitive:
SSN: 123-45-6789

Inline code samples:
Use `tx.Selection.FormattingStyle = "InlineCode";` to style inline fragments.
""";

var formatter = new JsonRegexInlineStyleFormatter();
int applied = formatter.Apply(tx, "rules.json");

tx.Save("styled.pdf", StreamType.AdobePDF);

Console.WriteLine($"Applied {applied} inline style matches.");

The result is a nicely formatted document in which important elements stand out visually:

Formatted Results

Conclusion

This approach provides a flexible way to style documents, eliminating the need to hardcode formatting rules into your application. Everything is driven by a JSON configuration.

  • Styles define how matches should appear.
  • Rules use RegEx to define what to detect.
  • The formatter applies inline styles directly through TX Text Control's selection logic.

This practical solution highlights important elements, such as dates, emails, IDs, bank accounts, phone numbers, and sensitive data, in generated documents while keeping the content editable and the implementation clean.

Feel free to explore the full sample on GitHub and adapt it to your needs. Contact us if you have any questions or need assistance.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • TX Text Control .NET Server 34.0
  • Visual Studio 2026

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreRegEx

Advanced Smart Search with Regular Expressions in .NET C#

This article shows how to extend the smart search feature of TX Text Control .NET with regular expressions. This allows you to search for complex patterns in documents such as email addresses,…


ASP.NETASP.NET CoreCSV

Convert CSV to PDF in .NET C#

Learn how to convert CSV data to a table in C# using the ServerTextControl library with this step-by-step tutorial. Easily generate PDF documents from CSV files in your .NET applications.


ASP.NETJavaScriptASP.NET Core

5 Document Workflows You Can Automate With JavaScript Rich Text Editor

Enterprise JavaScript rich text editors outperform open source and basic alternatives for document automation. This guide covers five document workflows with TX Text Control: contract generation…


ASP.NETAIASP.NET Core

AI-Ready Legal Documents: What to Fix Before Adding AI

Summerization, analysis, and risk detection: AI can help legal professionals process documents faster and more efficiently. However, before integrating AI into your legal document workflows, it's…


ASP.NETAIASP.NET Core

Explaining Contract Tracked Changes Automatically Using .NET C# and AI

Learn how to use AI and .NET C# to automatically explain changes to contracts, improving the document review and collaboration processes. This comprehensive guide provides practical implementation…

Summarize this blog post with:

Share on this blog post on: