Link to home
Start Free TrialLog in
Avatar of Dnx_7
Dnx_7Flag for Belgium

asked on

How to extract a path from a given string with REGEX in C#

Hi,

I would like to extract a path from any given string with a regex.
We can have multiple scenario like :

hi my name is G:\Assets\Resources\Firstname.png say hello!
G:\Assets\Resources\Firstname.png say hello!
Hi my name is G:\Assets\Resources\Firstname.png
G:\Assets\Resources\Firstname.png

In all cases, the result would be "G:\Assets\Resources\Firstname.png"

Can you help me to do that?


Thanks in advance,

Kind Regards.
SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'll need to have a closer look at that, but in the meanwhile I'd like to recommend the free tool program Expresso (d/l from here). It's a tool for designing and testing regular expressions.

I'll be back !
After playing a bit, I came to this one ... worked well in Expresso in a text stream of your examples. Maybe the \r\n part isn't needed for singular one line strings outside of a longer text.

([a-zA-Z]\:\\[\w\\\.]*)[\r\n ]+?.*

BTW: That works only if the path doesn't contain blanks. If the path contains blanks, the task would be an impossible one if there are no definite delimiters.

@Guy Hengel: Your solution seems to omit that the first character in the path must be a letter (not a number or special character). Beside of that it gives some strange results in Expresso ...
Avatar of louisfr
louisfr

If you consider only absolute paths without spaces in it, you can use the following regex:
[a-z]:(\\[^"<>|\u0000-\u001F:*?\\/])*

Open in new window

Avatar of Dnx_7

ASKER

hi,
Thanks all for the help.

frankhelk, it seems that your solution is the closest one but indeed, we can have space in path BUT file extension can be specified like '.png' or '.bmp', can you adapt the regex for me? the regex is definitely not my friend lol

louisfr the regex seems not to be valid...

Thanks!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial