-1

I have many strings like these

/test/v1/3908643GASF/item
/test/v1/343569/item/AAAS45663/document
/test/v2/field/1230FRE/item
...

For each one I need to extract the defined pattern like these

/test/v1/{Value}/item
/test/v1/{Value}/item/{Value}/document
/test/v2/field/{Value}/item

The value can be a guid or something else, Can I match the given string patterns with input paths with regex?

I wrote just this code but I don't konw how to match input paths with patterns. The result should be the pattern. Thank you

string pattern1 = "/test/v1/{Value}/item";
string pattern2 = "/test/v1/{Value}/item/{Value}/document";
string pattern3 = "/test/v2/field/{Value}/item";

List<string> paths = new List<string>();
List<string> matched = new List<string>();    

paths.Add("/test/v1/3908643GASF/item");
paths.Add("/test/v1/343569/item/AAAS45663/document");
paths.Add("/test/v1/343569/item/AAAS45664/document");
paths.Add("/test/v1/123444/item/AAAS45688/document");
paths.Add("/test/v2/field/1230FRE/item");


foreach (var path in paths)
{


}
Stefano Cavion
  • 641
  • 8
  • 16
nagy
  • 1
  • 2
  • I think you are searching for something like this: /(\/test\/v1\/[a-z, A-Z]+\/item)/ /(\/test\/v1\/[a-z, A-Z]+\/item\/[a-z, A-Z]+\/document)/ – Emanuele Jun 19 '20 at 10:12

1 Answers1

0

This can also be achieved using regex alone. You can probably try:

(\w+)\/\w+(?<=\/item)(\/(\w+)\/)?

Explanation of the above regex:

(\w+) - Represents a capturing group matching a word character one or more time. This group captures our required result.

\/\w+(?<=\/item) - Represents a positive look-behind matching the characters before \items.

$1 - Captured group 1 contains the required information you're expecting.

(\/(\w+)\/)? - Represents the second and third capturing group capturing if after item some other values is present or not.

You can find the demo of the above regex in here.


Pictorial Representation

Sample implementation in C#:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(\w+)\/\w+(?<=\/item)(\/(\w+)\/)?";
        string input = @"/test/v1/3908643GASF/item
/test/v1/343569/item/AAAS45663/document
/test/v2/field/1230FRE/item";
        
        foreach (Match m in Regex.Matches(input, pattern))
        {
            Console.Write(m.Groups[1].Value + " ");
            if(m.Groups[3].Value != null)
                Console.WriteLine(m.Groups[3].Value);
        }
    }
}

You can find the sample run of the above implementation in here.

Community
  • 1
  • 1
  • Hmm downvoter!!!I can improve my answer if there is something wrong. –  Jun 19 '20 at 12:35