# 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.

- **Author:** Bjoern Meyer
- **Published:** 2026-01-20
- **Modified:** 2026-07-17
- **Description:** 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.
- **4 min read** (782 words)
- **Tags:**
  - ASP.NET
  - ASP.NET Core
  - RegEx
  - Inline Styling
- **Web URL:** https://www.textcontrol.com/blog/2026/01/20/regex-based-inline-styling-in-tx-text-control-using-json-rules/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/01/20/regex-based-inline-styling-in-tx-text-control-using-json-rules/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/01/20/regex-based-inline-styling-in-tx-text-control-using-json-rules/llms-full.txt
- **GitHub Repository:** https://github.com/TextControl/TXTextControl.Core.RegExToStyle

---

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](https://s1-www.textcontrol.com/assets/dist/blog/2026/01/20/a/assets/results.webp "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.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [Advanced Smart Search with Regular Expressions in .NET C#](https://www.textcontrol.com/blog/2025/01/29/advanced-smart-search-with-regular-expressions-in-net-csharp/llms.txt)
- [Silicon Valley, Here We Come!](https://www.textcontrol.com/blog/2026/08/10/silicon-valley-here-we-come/llms.txt)
- [Against the Trend: Why We Still Believe in Transparent, Perpetual Software Licensing. And Why You Should Too](https://www.textcontrol.com/blog/2026/08/06/against-the-trend-transparent-perpetual-software-licensing/llms.txt)
- [Unlock the Full Value of Your TX Text Control License](https://www.textcontrol.com/blog/2026/08/06/unlock-the-full-value-of-your-tx-text-control-license/llms.txt)
- [Introducing TX Text Control Web Collaboration Preview for ASP.NET Core](https://www.textcontrol.com/blog/2026/08/05/introducing-tx-text-control-web-collaboration-preview-for-asp-net-core-document-editors/llms.txt)
- [Building Long-Term Trust with Digital Signatures and Timestamps in C# .NET](https://www.textcontrol.com/blog/2026/08/04/building-long-term-trust-with-digital-signatures-and-timestamps-in-c-sharp-dot-net/llms.txt)
- [AI Natural Language Document Generation with MCP and TX Text Control .NET](https://www.textcontrol.com/blog/2026/07/16/ai-natural-language-document-generation-with-mcp-server-and-tx-text-control-dotnet/llms.txt)
- [WeAreDevelopers World Congress Europe 2026 Wrap Up: Record Breaking Days in Berlin](https://www.textcontrol.com/blog/2026/07/13/wearedevelopers-world-congress-europe-2026-wrap-up-record-breaking-days-in-berlin/llms.txt)
- [C# Document Generation: A Developer's Guide for .NET](https://www.textcontrol.com/blog/2026/07/08/csharp-document-generation-developer-guide-for-dotnet/llms.txt)
- [Validating PDF/UA Documents in .NET C#: A Practical Guide](https://www.textcontrol.com/blog/2026/07/06/validating-pdf-ua-documents-in-dotnet-csharp/llms.txt)
- [See Text Control at WeAreDevelopers World Congress Europe 2026 in Berlin](https://www.textcontrol.com/blog/2026/07/06/see-text-control-at-wearedevelopers-world-congress-europe-2026-in-berlin/llms.txt)
- [DWX 2026 Wrap-Up: Four Days of Innovation, Conversations, and Enterprise Document Solutions](https://www.textcontrol.com/blog/2026/07/03/dwx-2026-wrap-up-four-days-of-innovation-conversations-and-enterprise-document-solutions/llms.txt)
- [Create SignFabric Envelopes from Mail Merge Templates in .NET C#](https://www.textcontrol.com/blog/2026/06/23/create-signfabric-envelopes-from-mail-merge-templates-using-dotnet-csharp/llms.txt)
- [Convert SSRS RDL Reports to DOCX and TX Text Control Templates in .NET C#](https://www.textcontrol.com/blog/2026/06/22/convert-ssrs-rdl-reports-to-docx-and-tx-text-control-templates-in-dotnet-csharp/llms.txt)
- [Export Document Tables to CSV in .NET C#](https://www.textcontrol.com/blog/2026/06/19/export-document-tables-to-csv-in-dotnet-csharp/llms.txt)
- [Major SignFabric Updates: Stronger Audit Trails, Validation, and Recipient Workflows](https://www.textcontrol.com/blog/2026/06/17/major-signfabric-updates-stronger-audit-trails-validation-and-recipient-workflows/llms.txt)
- [Text Control Expands North American Conference Presence with WeAreDevelopers World Congress North America](https://www.textcontrol.com/blog/2026/06/12/text-control-expands-north-american-conference-presence-with-wearedevelopers-world-congress-north-america/llms.txt)
- [Converting HTML to Markdown in C# .NET](https://www.textcontrol.com/blog/2026/06/11/converting-html-to-markdown-in-csharp-dot-net/llms.txt)
- [Beyond WebSockets: A Glimpse into the Future of Document Editing with WebAssembly](https://www.textcontrol.com/blog/2026/06/10/beyond-websockets-glimpse-future-document-editing-webassembly/llms.txt)
- [Showcasing the Future of Document Processing at Developer World DWX 2026](https://www.textcontrol.com/blog/2026/06/08/showcasing-the-future-of-document-processing-at-dwx-developer-week-2026/llms.txt)
- [PDF Security Explained: Passwords, Permissions, Encryption and Digital Signatures in C# .NET](https://www.textcontrol.com/blog/2026/06/08/pdf-security-explained-passwords-permissions-encryption-and-digital-signatures-in-csharp-dotnet/llms.txt)
- [NDC Copenhagen 2026: Great Days in the Heart of Copenhagen's Developer Community](https://www.textcontrol.com/blog/2026/06/05/ndc-copenhagen-2026-great-days-in-the-heart-of-copenhagens-developer-community/llms.txt)
- [Automatically Mapping TX Text Control Form Fields to JSON Data in .NET C#](https://www.textcontrol.com/blog/2026/06/03/automatically-mapping-tx-text-control-form-fields-to-json-data-in-dotnet-csharp/llms.txt)
- [Getting Started with SignFabric: From Clone to Your First Signature Envelope](https://www.textcontrol.com/blog/2026/06/02/getting-started-with-signfabric-from-clone-to-your-first-signature-envelope/llms.txt)
- [We Never Pause - Join Us at NDC Copenhagen 2026](https://www.textcontrol.com/blog/2026/05/27/we-never-pause-join-us-at-ndc-copenhagen-2026/llms.txt)
