Convert wildcard to regular expression

I am new to regular expressions. Recently, I was tasked with converting a wildcard to a regular expression. This will be used to verify that the path file matches the regular expression.

For example, if my template is *.jpg;*.png;*.bmp

I managed to generate a regular expression by separating semicolons, tearing a line and replacing the escaped * with .*

 String regex = "((?i)" + Regex.Escape(extension).Replace("\\*", ".*") + "$)"; 

So, my resulting expression will be for jpg ((?i).*\.jpg)$) Thien I am combining all my extensions with the OR operator.

So my final expression for this example would be:

 ((?i).*\.jpg)$)|((?i).*\.png)$)|((?i).*\.bmp)$) 

I tested it and it worked, but I'm not sure if I have to add or remove any expression to cover other cases, or there is a better format.

Also remember that I can meet a wildcard, for example *myfile.jpg , where it must match all files whose names end in myfile.jpg

I can find such patterns as *myfile.jpg;*.png;*.bmp

+4
source share
1 answer

There is a lot of band that you don’t need ... well, if there is something you haven’t mentioned, this regular expression will do the same:

  /.*\.(jpg|png|bmp)$/i 

This is in the regex notation, in C #, which will be:

 String regex=new RegEx(@".*\.(jpg|png|bmp)$",RegexOptions.IgnoreCase); 

If you need to programmatically translate between the two, you started on the right track - separated by a semicolon, grouped your extensions into a set (without the previous dot). If your wildcard patterns can be more complex (wildcard extensions, matches with multiple wildcards), you may need a little more work;)

Edit: (for your update)

If wild cards can be more complex, then you are almost there. In my code above there is an optimization that draws a point (for extension) that needs to be returned so you can:

  /.*(myfile\.jpg|\.png|\.bmp)$/i 

Mostly '*' β†’ '. * ','. ' β†’ '\.' (slips away), rest turns into a set. Basically, he says that something ends (the dollar sign is tied to the end) in myfile.jpg , .png or .bmp .

+8
source

Source: https://habr.com/ru/post/1437450/


All Articles