Skip to main content

How to Match Messages with a Regular Expression in the Microsoft 365 Agents SDK in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

OnMessage("help", ...) only matches a message that is exactly help. Messages that carry a value, such as add 2 and 3, need a pattern: give OnMessage a regular expression instead, and read the values from the pattern in your handler.

Syntax​

C#
OnMessage(new Regex(pattern, options), handler);
  • pattern is the regular expression the message's text must match. The SDK checks it with Regex.IsMatch, which finds a match anywhere in the text, so start the pattern with ^ and end it with $ when it should match the whole message.
  • options is optional. RegexOptions.IgnoreCase accepts any capitalization; without it, the match is case-sensitive.
  • handler is the method that runs when the pattern matches, with the signature Task Name(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken).

OnMessage is a method of AgentApplication; call it in your agent's constructor. It also takes an optional rank, which decides the order your routes are tried in.

The Example​

The agent for this post is a tiny calculator. Send it add 2 and 3, and it answers 2 + 3 = 5:

CalculatorAgent.cs
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;

namespace RegexDemo;

public class CalculatorAgent : AgentApplication
{
// "add", a number, "and", another number. Up to nine digits each, so the sum always fits in an int.
private static readonly Regex AddPattern = new(@"^add (\d{1,9}) and (\d{1,9})$", RegexOptions.IgnoreCase);

public CalculatorAgent(AgentApplicationOptions options) : base(options)
{
OnMessage(AddPattern, AddAsync);
}

private async Task AddAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// The route matched, so the pattern matches: read the two numbers from its groups.
Match match = AddPattern.Match(turnContext.Activity.Text);
int first = int.Parse(match.Groups[1].Value);
int second = int.Parse(match.Groups[2].Value);

await turnContext.SendActivityAsync($"{first} + {second} = {first + second}", cancellationToken: cancellationToken);
}
}

CalculatorAgent.cs in a macOS-style editor window: a static Regex AddPattern with two groups of up to nine digits and RegexOptions.IgnoreCase, a constructor that calls OnMessage with the pattern and AddAsync, and an AddAsync handler that matches the text again, parses both groups with int.Parse and sends the sum

It's one class in an ASP.NET Core project with the Agents SDK, hosted with AddAgent<CalculatorAgent>() and listening on port 3978.

Prerequisites​

  • The Microsoft 365 Agents Playground, to send the agent messages on your own machine. agentsplayground --version should print 0.2.30; if the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.

Step 1: Write the Pattern​

Write the pattern once, as a static readonly field, so it's built when the class is first used and not again for every message:

CalculatorAgent.cs (the pattern)
private static readonly Regex AddPattern = new(@"^add (\d{1,9}) and (\d{1,9})$", RegexOptions.IgnoreCase);

Read it from left to right:

  • ^ is the start of the message, and $ its end, so the whole message must fit the pattern.
  • add and and are the words, spaces included.
  • (\d{1,9}) is one to nine digits. The brackets make it a group, a part of the match you can read later. The two groups are numbered 1 and 2, from left to right.
  • RegexOptions.IgnoreCase lets Add and ADD match too.

Nine digits is a limit on purpose: the largest sum, 999999999 + 999999999, still fits in an int, so the handler never fails on a number that's too long.

Step 2: Register the Route​

Pass the pattern to OnMessage in the constructor:

CalculatorAgent.cs (the constructor)
public CalculatorAgent(AgentApplicationOptions options) : base(options)
{
OnMessage(AddPattern, AddAsync);
}

The route matches only message activities, and only when their text matches the pattern.

Step 3: Read the Values in the Handler​

The route only tells the handler that the pattern matched. To get the numbers, match again and read the groups:

CalculatorAgent.cs (the handler)
private async Task AddAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// The route matched, so the pattern matches: read the two numbers from its groups.
Match match = AddPattern.Match(turnContext.Activity.Text);
int first = int.Parse(match.Groups[1].Value);
int second = int.Parse(match.Groups[2].Value);

await turnContext.SendActivityAsync($"{first} + {second} = {first + second}", cancellationToken: cancellationToken);
}

match.Groups[1].Value is the text of the first group, such as 2. int.Parse is safe here, because the pattern only lets through one to nine digits.

Step 4: Try It​

Run the agent with dotnet run, start the Agents Playground in a second terminal, and send four messages: add 2 and 3, Add 40 and 2, add two and three and please add 2 and 3.

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c emulator

The Agents Playground chat: add 2 and 3 gets 2 + 3 = 5, Add 40 and 2 gets 40 + 2 = 42, and add two and three and please add 2 and 3 get no answer

  • add 2 and 3 matched and got its sum.
  • Add 40 and 2 matched too, thanks to RegexOptions.IgnoreCase.
  • add two and three has no digits, so it didn't match.
  • please add 2 and 3 contains a matching phrase, but ^ requires add at the very start, so it didn't match either.

The last two got no answer at all, because this agent has no other route: an activity no route matches is accepted and ignored. To answer those too, add a catch-all route, as How to Add a Catch-All Route in the Microsoft 365 Agents SDK in C# shows.

Common Mistakes​

MistakeWhat happensDo this instead
A pattern without ^ and $It matches inside longer messages, such as I don't want to add 2 and 3Anchor the pattern to the whole message
Forgetting RegexOptions.IgnoreCaseAdd 40 and 2 gets no answerPass RegexOptions.IgnoreCase, or write the pattern for every capitalization
\d+ with int.ParseA long enough number throws an OverflowExceptionLimit the digits, as \d{1,9} does, or use int.TryParse
Creating the Regex inside the handlerThe pattern is built again for every messageKeep it in a static readonly field

Troubleshooting​

SymptomLikely causeFix
No answer, and the Log Panel shows message 202The text doesn't match the patternCompare the text with the pattern character by character, spaces included
Add 40 and 2 gets no answer, add 40 and 2 doesThe pattern is case-sensitiveAdd RegexOptions.IgnoreCase
An exact-text route answers insteadAnother route that matches the same message is tried firstCheck the order of your routes and their ranks

FAQ​

Can I use named groups?​

Yes. Write (?<first>\d{1,9}) in the pattern and read match.Groups["first"].Value in the handler. Names make long patterns easier to read than numbers.

Do I have to match the pattern twice?​

The route uses the pattern only to decide; it doesn't pass the match to your handler. Matching once more in the handler is cheap, and it's the simplest way to read the values.

What does OnMessage with a string do instead?​

It compares the whole message text with the string, ignoring case. OnMessage("help", ...) matches help and HELP, but not help me.

Conclusion​

To route messages by pattern, give OnMessage a Regex: anchor it with ^ and $, add RegexOptions.IgnoreCase when capitalization shouldn't matter, and keep it in a static readonly field. In the handler, match again and read the values from the pattern's groups. Messages that don't fit the pattern skip the route, so pair it with a catch-all if they need an answer.

Additional Resources​