What Regular Expression Would I Use to Remove Everything After the Second Backslash

How to delete everything after second slash

Use an expression ^([^/]*/[^/]*/).*$, and replace with $1

enter image description here

([^/]*/[^/]*/) expression captures the part that you want to keep; .*$ captures the rest of the string to the end of line. Replacing with $1 removes the unwanted portion of the string.

Remove everything after a changing string

with cut:

cut -d\/ -f1,2,3 file

Regex for matching everything after second-to-last backslash

You can use

@"[^\\]+\\[^\\]+$"

See regex demo

The [^\\]+\\[^\\]+$ matches

  • [^\\]+ - 1 or more symbols other than \
  • \\ - a literal \
  • [^\\]+ - 1 or more symbols other than \
  • $ - end of string.

In C#, a more efficient way to match some substring at the end is using RegexOptions.RightToLeft modifier. Use it to make this regex search more efficient.

C# demo:

var line = @"0001 Lorem ipsum dolor sit\011 tortor neque\ 0111\interdum magn";
var pattern = @"[^\\]+\\[^\\]+$";
var result = Regex.Match(line, pattern, RegexOptions.RightToLeft);
if (result.Success)
Console.WriteLine(result.Value); // => " 0111\interdum magn"

Just a comparison of the regex effeciency with and without RTL option at regexhero.net:

enter image description here

Regular Expression for getting everything after last slash

No, an ^ inside [] means negation.

[/] stands for 'any character in set [/]'.

[^/] stands for 'any character not in set [/]'.

Regular Expression, remove everything after last forward slash

Replace /[^/]*$ with an empty string

Regex for remove everything after | (with | )

The pipe, |, is a special-character in regex (meaning "or") and you'll have to escape it with a \.

Using your current regex:

\|.*$

I've tried this in Notepad++, as you've mentioned, and it appears to work well.

Remove everything after last backslash

You need lastIndexOf and substr...

var t = "\\some\\route\\here";
t = t.substr(0, t.lastIndexOf("\\"));
alert(t);

Also, you need to double up \ chars in strings as they are used for escaping special characters.

Update
Since this is regularly proving useful for others, here's a snippet example...