Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try this sample:</p> <pre><code>string fileName = @"X:\Users\username\AppData\Local\foo.txt"; Console.Write(Regex.Replace(fileName, @"([A-Z]{1}\:*\\Users\\)(\w+\\)(.*)", "$1$3")); </code></pre> <p>Explanation:</p> <ol> <li><code>([A-Z]{1}\:\\[Uu]sers\\)</code> - this part of Regex is a first group of characters, before the <code>username</code>, in the path<br> <ul> <li><code>^</code> stands for the start of the line <strong>(remove this to ignore words preceding the filename)</strong> </li> <li><code>[A-Z]{1}\:\\</code> stands for the disk root path. You can choose the disk letters you want to be here, like this: <code>[CDX-Z]{1}</code>. Note <code>{1}</code> - this is constraint means you need only 1 uppercase letter.</li> <li><code>[Uu]sers\\</code> stands for the users directory name, note the group for the case-insensitive users path This is first group, refered as <code>$1</code> in the replace pattern </li> </ul></li> <li><code>(\w+\\)</code> - this part of Regex is a second group of characters, the <code>username</code>, in the path <ul> <li><code>\w+\\</code> stands for at least one word character and <code>\</code> sign. This is a second group, which is not in a replace pattern </li> </ul></li> <li><code>(.*)</code> - this part of Regex is a third group of characters, after the <code>username</code>, in the path<br> <ul> <li><code>.*</code> stands for any character after the removed <code>\</code> symbol.</li> </ul></li> </ol> <p>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 <code>\</code> sign.</p> <pre><code>string fileName = @"X:\Users\username\AppData\Local\foo.txt"; Console.Write(Regex.Replace(fileName, @"([A-Z]{1}\:\\[Uu]sers\\)([^\\]*\\)(.*)", "$1$3")); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload