user1158745
user1158745

Reputation: 2490

Regular expression to remove part of a string

I am kinda new to regex, I have a string e.g

String test = @"c:\test\testing";

Now what I would like to accomplish is to removing all words up to "\". So in this case the work being removed is "testing". Howerver, this word may be different everytime. So bascally remove everyting until the first \ is found.

Any ideas?

Upvotes: 1

Views: 9378

Answers (7)

Meysam
Meysam

Reputation: 18137

You can do this without regex:

String test = @"c:\test\testing";
int lastIndex = test.LastIndexOf("\");
test = test.Remove(0, lastIndex >= 0 ? lastIndex : 0);

Upvotes: 1

Dr. Wily's Apprentice
Dr. Wily's Apprentice

Reputation: 10280

You can use the following regex pattern:

(?!\\)([^\\]*)$

Do a replace on this pattern with the empty string, as shown below:

var re = new Regex(@"(?!\\)([^\\]*)$");

var result = re.Replace(@"c:\test\testing", string.Empty);

Console.WriteLine(result);

However, consider using the System.IO namespace, specifically the Path class, instead of Regex.

Upvotes: 4

RvdK
RvdK

Reputation: 19790

I prefer to use the DirectoryInfo for this, or even a substring action.

DirectoryInfo dir = new DirectoryInfo(@"c:\test\testing");
String dirName = dir.Name;

Upvotes: 1

Ben M
Ben M

Reputation: 22492

You mean remove backwards, until the first \ is found?

You could easily do this without regexes:

var lastIndex = myString.LastIndexOf('\\');
if (lastIndex != -1)
{
    myString = myString.Substring(0, lastIndex + 1); // keep the '\\' you found
}

But if you're really just trying to get the directory component of a path, you can use this:

var directoryOfPath = System.IO.Path.GetDirectoryName(fullPath);

Although IIRC that method call will strip the trailing backslash.

Upvotes: 6

Mithrandir
Mithrandir

Reputation: 25337

If you want to "remove" or manipulate file paths, you can skip the basic Regex class altogether and use the class Path from System.IO. This class will give you suitable methods for all you needs in changing/extracting file names.

Upvotes: 0

rerun
rerun

Reputation: 25495

regex.replace(str,"^.*?\\","");

Upvotes: 1

Oybek
Oybek

Reputation: 7243

Try this \\\w+$ and replace it with \

Or you can use the following approach

(?<=\\)\w+$ In this case you just replace the match with an empty string.

Upvotes: 1

Related Questions