web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Power Platform Community / Forums / Power Automate / Custom Conenctor: Rege...
Power Automate
Answered

Custom Conenctor: Regex Match and Replace

(1) ShareShare
ReportReport
Posted on by 414 Super User 2024 Season 1

Hello All,

I wish to share my expansion of a pretty nice Custom Connector by MattyBeard: PowerAutomate_CustomConnectors/RegexReplace at master · mattybeard/PowerAutomate_CustomConnectors (github.com)

 

Their specific connector only performs "replace". I expanded this idea and appended match and replace into one single connector with no authentication required. PowerAutomate_CustomConnectors/Alexanders RegEx (independent Publisher) at master · AlexanderWorley/PowerAutomate_CustomConnectors (github.com)

 

Keep in mind the function "matches" is not available through this, but you can use Apply To Each to emulate matches as long as your items are in the array format of ["object1","object2"]. If your list is set as a string you can use expressions like split and replace to brute force the list into the aforementioned array format. This is really handy for parsing multiple selections in MS Forms submissions!

 

example: To parse emails from a MS form submission from a Multiple selection question you can use this to export the function as the array then use the match function of the custom connector to iterate through all items! 

 

Input text: "["test@test.com","test2@test.com","test3@test.com"]" (note the quotes as MS Forms exports the array as a string.... for some reason...)

 

(into the input of the apply to each) Expression input: split(replace(replace(replace(outputs('Compose'),']',''),'[',''),'"',''),',')

Output text: 

[\\"test@test.com",\\"test2@test.com",\\"test3@test.com"]

 

Apply to Each:

(Selects email addresses)Match pattern: [A-Za-z0-9_]+@[A-Za-z0-9]+\.[A-Za-z]+

 

Append to Array variable: outputs(Alexander's_RegEx_Match)?['body/output']

 

Output:  ["test@test.com","test2@test.com","test3@test.com"]

 

If you want to use this array for email automation purposes you can convert the array using the "join" action and having the "join with" field as a semicolon. ' ; '

 

I thought this was really neat and cool as other solutions either require an excel script OR annoyingly a subscription to 3rd party APIs. 

 

Categories:
  • Verified answer
    v-yujincui-msft Profile Picture
    Microsoft Employee on at

    Hi @AWorley ,

     

    Thanks for sharing. 

    Maybe you could consider adding a reply and mark it as a 'Solution', it will make it easier for other users to identify your case. 

    Cheers! 

     

     

    Best Regards, 
    Charlie Choi
     

  • CU23070509-2 Profile Picture
    on at

    Hi @AWorley 

    Thank you for this combined connector, that is very usefull in my use case.

     

    I would like to know if would be possible to extract multiple email addresses from a text like this: "For this matter please contact x@domain.com or y@domain.com or call 111-222". In this moment I will get only the first email address but not the second one.

     

    Kind Regards,

    Lucian

  • Lucian Profile Picture
    256 on at

    Hi @AWorley 

     

    I managed to create the connector, except when testing, it seems that it does not consider space as a word boundary, or there is something else, because in the test phrase:

     

    This text contains email addresses, such as paulie@domain.com and steve@domain.net – also peter@somedomain.co.uk has been included and sarah@saralee.com is here too.

    using the pattern

    \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}\b

     it will return

    {
     "output": "paulie@domain.com and"
    }

     

    Am I doing something wrong?

     

    Kind Regards,

    Lucian

  • AWorley Profile Picture
    414 Super User 2024 Season 1 on at

    Hi! your pattern and mine differ slightly but i was able to make adjustments with it to make it work.

     

    my pattern: [A-Za-z0-9_]+@[A-Za-z0-9]+\.[A-Za-z]+

     

    AWorley_0-1681146063793.png

     

     

    In my original post I described how to do the matches with power automate. 

     

    Tinkering with your regex pattern I managed to achieve the result as well my changing the number in the end brackets from "2," to just 1.

     

    new pattern:  \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+.[A-Za-z]{1}\b

     

    AWorley_1-1681146330912.png

     

  • AWorley Profile Picture
    414 Super User 2024 Season 1 on at

    yes, you just need to do a new regex pattern. in order to do multiple matches, you have to do some array magic I described this in the original post:

     

     

     

    Keep in mind the function "matches" is not available through this, but you can use Apply To Each to emulate matches as long as your items are in the array format of ["object1","object2"]. If your list is set as a string you can use expressions like split and replace to brute force the list into the aforementioned array format. This is really handy for parsing multiple selections in MS Forms submissions!

     

    example: To parse emails from a MS form submission from a Multiple selection question you can use this to export the function as the array then use the match function of the custom connector to iterate through all items! 

     

    Input text: "["test@test.com","test2@test.com","test3@test.com"]" (note the quotes as MS Forms exports the array as a string.... for some reason...)

     

    (into the input of the apply to each) Expression input: split(replace(replace(replace(outputs('Compose'),']',''),'[',''),'"',''),',')

    Output text: 

    [\\"test@test.com",\\"test2@test.com",\\"test3@test.com"]

     

    Apply to Each:

    (Selects email addresses)Match pattern: [A-Za-z0-9_]+@[A-Za-z0-9]+\.[A-Za-z]+

     

    Append to Array variable: outputs(Alexander's_RegEx_Match)?['body/output']

     

    Output:  ["test@test.com","test2@test.com","test3@test.com"]

     

    If you want to use this array for email automation purposes you can convert the array using the "join" action and having the "join with" field as a semicolon. ' ; '

     

     

  • Lucian Profile Picture
    256 on at

    Hi @AWorley ,

     

    Thank you for your message and pointing me out the pattern mistake. I'm still struggling to understand it 😜.

    Finally, with your help and the extra help from https://regex101.com/ I found the correct pattern:

     

    \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+\.[A-Za-z]{2,}\b

     

    The problem it was I did not "escaped" the "." in my initial pattern that matched any character instead of the literal ".".

     

    Also I've managed to derive your "match" function to get all the matches:

     private async Task<HttpResponseMessage> PerformRegexMatches()
     { 
     // Manipulate the request data as applicable before setting it back
     var requestContentAsString = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
     var requestContentAsJson = JObject.Parse(requestContentAsString);
    
     var input = (string)requestContentAsJson["input"];
     var pattern = (string)requestContentAsJson["pattern"];
     
     MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(1));
     string result= "";
    
     var toarray = from Match match in matches select match.Value;
     
     // Manipulate the response data as applicable before returning it
     JObject output = new JObject
     {
     ["output"] = JArray.FromObject(toarray)
     };
    
     var response = new HttpResponseMessage(HttpStatusCode.OK);
     response.Content = CreateJsonContent(output.ToString());
     return response;
     }

    And now I could extract all the email addresses from the test phrase above and use it into an array variable along with apply to each action.

     

    Thank you again for sharing this great "custom connector". 

     

    Kind Regards,

    Lucian

  • Dion_tw Profile Picture
    66 on at

    I copied your code the retreive multiple matches but i got an error saving the custom connector. Am I missing something besides the provided code?

  • Lucian Profile Picture
    256 on at

    Hi @Dion_tw ,

     

    Yes, it might be some missing parts, because in the "ScriptBase" section I was modify it to have the call to the new function.

     

    So, I have pasted below the entire code I'm using:

    using System.Threading.Tasks;
    using System.Net.Http;
    using Newtonsoft.Json.Linq;
    using System.Text.RegularExpressions;
    using System.Net;
    
    public class Script : ScriptBase
    {
     public override async Task<HttpResponseMessage> ExecuteAsync()
     {
     if (this.Context.OperationId == "RegexReplace")
     {
     return await this.PerformRegexReplace().ConfigureAwait(false);
     }else if(this.Context.OperationId == "RegexMatch") {
     return await this.PerformRegexMatch().ConfigureAwait(false);
     }else if(this.Context.OperationId == "RegexMatches") {
     return await this.PerformRegexMatches().ConfigureAwait(false);
     }
    
     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
     response.Content = CreateJsonContent($"Unknown operation ID '{this.Context.OperationId}'");
     return response;
     }
    private async Task<HttpResponseMessage> PerformRegexReplace()
     { 
     // Manipulate the request data as applicable before setting it back
     var requestContentAsString = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
     var requestContentAsJson = JObject.Parse(requestContentAsString);
    
     var input = (string)requestContentAsJson["input"];
     var pattern = (string)requestContentAsJson["pattern"];
     var replacement = (string)requestContentAsJson["replacement"];
    
     var regexResult = Regex.Replace(input, pattern, replacement);
    
     // Manipulate the response data as applicable before returning it
     JObject output = new JObject
     {
     ["output"] = regexResult
     };
    
     var response = new HttpResponseMessage(HttpStatusCode.OK);
     response.Content = CreateJsonContent(output.ToString());
     return response;
     }
     private async Task<HttpResponseMessage> PerformRegexMatch()
     { 
     // Manipulate the request data as applicable before setting it back
     var requestContentAsString = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
     var requestContentAsJson = JObject.Parse(requestContentAsString);
    
     var input = (string)requestContentAsJson["input"];
     var pattern = (string)requestContentAsJson["pattern"];
     
    
     var regexResult = Regex.Match(input, pattern).Value;
    
     // Manipulate the response data as applicable before returning it
     JObject output = new JObject
     {
     ["output"] = regexResult
     };
    
     var response = new HttpResponseMessage(HttpStatusCode.OK);
     response.Content = CreateJsonContent(output.ToString());
     return response;
     }
     private async Task<HttpResponseMessage> PerformRegexMatches()
     { 
     // Manipulate the request data as applicable before setting it back
     var requestContentAsString = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
     var requestContentAsJson = JObject.Parse(requestContentAsString);
    
     var input = (string)requestContentAsJson["input"];
     var pattern = (string)requestContentAsJson["pattern"];
     
     MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(1));
     string result= "";
    
     var toarray = from Match match in matches select match.Value;
     
     // Manipulate the response data as applicable before returning it
     JObject output = new JObject
     {
     ["output"] = JArray.FromObject(toarray)
     };
    
     var response = new HttpResponseMessage(HttpStatusCode.OK);
     response.Content = CreateJsonContent(output.ToString());
     return response;
     } 
    }

     

    Also here is the modified Swagger file:

    swagger: '2.0'
    info:
     title: Power Automate RegEx
     description: >-
     Custom connector for dealing with RegEx
    
     https://powerusers.microsoft.com/t5/General-Power-Automate/Custom-Conenctor-Regex-Match-and-Replace/td-p/1746588
    
     https://ansrikanth.com/2022/02/23/regex-replace-in-power-automate-flows/
     version: '1.0'
    host: microsoft.com
    basePath: /
    schemes:
     - https
    consumes: []
    produces: []
    paths:
     /regexReplace:
     post:
     responses:
     default:
     description: default
     schema:
     type: object
     properties:
     output:
     type: string
     description: output
     summary: Alexander's RegEx Replace
     description: RegEx replace built into Power Automate
     operationId: RegexReplace
     parameters:
     - name: body
     in: body
     required: false
     schema:
     type: object
     properties:
     input:
     type: string
     description: input
     pattern:
     type: string
     description: pattern
     replacement:
     type: string
     description: replacement
     /regexMatch:
     post:
     responses:
     default:
     description: default
     schema:
     type: object
     properties:
     output:
     type: string
     description: output
     summary: Alexander's RegEx Match
     description: RegEx Match built into Power Automate
     operationId: RegexMatch
     parameters:
     - name: body
     in: body
     required: false
     schema:
     type: object
     properties:
     input:
     type: string
     description: input
     pattern:
     type: string
     description: pattern
     /regexMatches:
     post:
     responses:
     default:
     description: default
     schema:
     type: object
     properties:
     output:
     type: array
     items:
     type: string
     description: output
     summary: RegEx Multiple Matches
     description: RegEx Matches built into Power Automate
     operationId: RegexMatches
     parameters:
     - name: body
     in: body
     required: false
     schema:
     type: object
     properties:
     input:
     type: string
     description: input
     pattern:
     type: string
     description: pattern
    definitions: {}
    parameters: {}
    responses: {}
    securityDefinitions: {}
    security: []
    tags: []

     

    It shoud work now.

     

    Kind Regards,

    Lucian

  • Dion_tw Profile Picture
    66 on at

    Thanks a lot! I worked for some time but suddenly I received a 403 error the the web app has blocked my access?

    Does this have something to do with the host and/or url de connector is trying to connect to?

  • Lucian Profile Picture
    256 on at

    Hi @Dion_tw ,

    If worked once and you did not changed anything, the only idea I have is to renew you connection.

    This means you should go to Data > Connections, delete the current connection and when you edit your flow it would create a new connection to it.

     

    Hope this helps.

    Kind Regards,

    Lucian

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Kudos to our 2025 Community Spotlight Honorees

Expanding mentorship, skilling, and AI innovation

Leaderboard > Power Automate

#1
Mohsin Ali Profile Picture

Mohsin Ali 289

#2
11manish Profile Picture

11manish 282 Super User 2026 Season 2

#3
Henil Profile Picture

Henil 119

Last 30 days Overall leaderboard