简体   繁体   中英

How to extract file location using Regular Expressions(VB.NET)

I am facing a problem whereby I am given a string that contains a path to a file and the file's name and I only want to extract the path (without the file's name)

For example, I will receive something like

C:\\Users\\OopsD\\Projects\\test.acdbd

and from that string I want to extract only

C:\\Users\\OopsD\\Projects

I was trying to create a RegEx to match a backslash followed by a word, followed by a dot followed by another word - this is to match the

\\test.acdbd

part and replace it with empty string so that the final result is

C:\\Users\\OopsD\\Projects

Can anyone, familiar with RegEx, help me on this one? Also, I will be using regular expressions quite a lot in the future. Is there a (free) program I can download to create regular expressions?

The regex that you are looking for is as below:

[^/]+$

where, ^ (caret): Matches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the caret match after line breaks (ie at the start of a line in a file) as well.

$ (dollar): Matches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the dollar match before line breaks (ie at the end of a line in a file) as well. Also matches before the very last line break if the string ends with a line break.

+ (plus): Repeats the previous item once or more. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only once.

More reference can be found out at this link.

Many Regex softwares and tools are out there. Some of them are:

  1. www.gskinner.com/RegExr/
  2. www.txt2re.com
  3. Rubular - It is not just for Ruby.

Are you really sure you need to be using Regex for such as simple task? How about this:

Dim file As New IO.FileInfo(" C:\Users\OopsD\Projects\test.acdbd")
MsgBox(file.Directory.FullName)

Regarding the free program on Regex, I would definitely recommend http://www.gskinner.com/RegExr/ - using it all the time. But you always have to consider alternatives, before going the Regex way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM