简体   繁体   中英

Remove dynamic username from file path

I have the following in C#.

string fileName = @"X:\Users\username\AppData\Local\foo.txt";

I want to perform a Regex.Replace so that I get the following back.

string fileName = @"X:\Users\AppData\Local\foo.txt";

It would be nice to use a Regex that allows for the drive letter ( X: ) to be dynamic. In essence, I just need to drop the ' username ' part. Also, note that username is just a placeholder for the user's actual name - so that could be bob or larry or john or anything else. The Regex will need to take this into account.

The thing that you can count on here is that it will always start with X:\\Users\\ (where X: can be C: or D: , etc.) and then will be followed with some string and then will be followed by a \\ and then some other path elements that are not important. Also, it would be good to have a case-insensitive match on users or Users .

I know that this can be done without Regex , but I need this to fit into a larger system that only provides Regex support. There's no support for things like String.Replace or String.Join .

You can try this sample:

string fileName = @"X:\Users\username\AppData\Local\foo.txt";
Console.Write(Regex.Replace(fileName, @"([A-Z]{1}\:*\\Users\\)(\w+\\)(.*)", "$1$3"));

Explanation:

  1. ([AZ]{1}\\:\\\\[Uu]sers\\\\) - this part of Regex is a first group of characters, before the username , in the path
    • ^ stands for the start of the line (remove this to ignore words preceding the filename)
    • [AZ]{1}\\:\\\\ stands for the disk root path. You can choose the disk letters you want to be here, like this: [CDX-Z]{1} . Note {1} - this is constraint means you need only 1 uppercase letter.
    • [Uu]sers\\\\ stands for the users directory name, note the group for the case-insensitive users path This is first group, refered as $1 in the replace pattern
  2. (\\w+\\\\) - this part of Regex is a second group of characters, the username , in the path
    • \\w+\\\\ stands for at least one word character and \\ sign. This is a second group, which is not in a replace pattern
  3. (.*) - this part of Regex is a third group of characters, after the username , in the path
    • .* stands for any character after the removed \\ symbol.

Update: In the real world I found usernames with spaces, unicode chars and ~ in it. So I replaced the 2. group to include any characters but the \\ sign.

string fileName = @"X:\Users\username\AppData\Local\foo.txt";
Console.Write(Regex.Replace(fileName, @"([A-Z]{1}\:\\[Uu]sers\\)([^\\]*\\)(.*)", "$1$3"));

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