Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression issuse

Tags:

c#

regex

I'm having some troubles to write a regular expression.

I have to extract some informations from a string and identify very specific parts in it.

All parts are not mandatory.

My format is : ORDER_filename.extension(options) where filename is mandatory, and ORDER, extension and options are not.

For exemple, I may have :

100_Some file name.ext(3)
_Some other file name.ext
300_Folder name
400_Another Folder name(5)

I should be able to extract :

Order  |   Filename                 |  extension | options
----------------------------------------------------------
100    |   Some file name           |  ext       | 3
(null) |   _Some other file name    |  ext       | (null)
300    |   Folder name              |  (null)    | (null)
400    |   Another Folder name      |  (null)    | 5

The second line has the underscore in the filename.

I'm playing with regex lib a bit, but I did not succeed in extracting all my parts.

I tried:

  • ^(?<order>[0-9_]+_)?(?<filename>\w+) : but it splits the filename at space
  • ^(?<order>[0-9_]+_)?(?<filename>\w+)(\.(?<ext>.+))?: no extension is extracted. File name is still split.
  • ^(?<order>[0-9_]+_)?(?<filename>\w+)(\.(?<ext>.+))?(\((?<options>.+)\))?: neither extension nor options are extracted. File name is still split.

What is the correct expression I should use?

FYI, I'll use the C# named captures to do some job using these values.

like image 290
Steve B Avatar asked Sep 24 '26 14:09

Steve B


1 Answers

Nevermind,

I misunderstood the \w alias. This does not includes the spaces.

This expression is working as expected :

^(?<order>[0-9_]+_)?(?<filename>(\w|\s)+)(\.(?<ext>\w+))?(\((?<options>.+)\))?

[Edit] Unfortunately, there are some cases where this explode :

100_some file() name.doc(3)
like image 66
Steve B Avatar answered Sep 26 '26 03:09

Steve B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!