Removing Everything After First 'Backslash' in a String

removing everything after first 'backslash' in a string

another solution :

 sub("\\\\.*", "", x)

Removing everything after the first backslash

To avoid such errors, add a fail-safe. Notice the + '\'

EXAMPLE

LEFT(column_name_goes_here, CHARINDEX('\', column_name_goes_here + '\') - 1)

Remove everything after backslash in base R?

Here is another way you could try:

gsub("(^\\d+)([\a-zA-Z0-9]*)", "\\1", myString)

[1] "5" "10" "100"

Remove everything before the first forward slash in the url

I understand the questions asks for regex but the need is unclear - if all you need is the path name there are better tools in the toolbox (for anybody not working on a homework exercise).

const url = 'https://stackoverflow.com/questions/ask'
console.log(new URL(url).pathname)

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...

// the original stringvar t = "\\some\\route\\here";
// remove everything after the last backslashvar afterWith = t.substr(0, t.lastIndexOf("\\") + 1);
// remove everything after & including the last backslashvar afterWithout = t.substr(0, t.lastIndexOf("\\"));
// show the resultsconsole.log("before : " + t);console.log("after (with \\) : " + afterWith);console.log("after (without \\) : " + afterWithout);

Remove everything after a changing string

with cut:

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

Remove Part of String Before the Last Forward Slash

Have a look at str.rsplit.

>>> s = 'https://docs.python.org/3.4/tutorial/interpreter.html'
>>> s.rsplit('/',1)
['https://docs.python.org/3.4/tutorial', 'interpreter.html']
>>> s.rsplit('/',1)[1]
'interpreter.html'

And to use RegEx

>>> re.search(r'(.*)/(.*)',s).group(2)
'interpreter.html'

Then match the 2nd group which lies between the last / and the end of String. This is a greedy usage of the greedy technique in RegEx.

Regular expression visualization

Debuggex Demo

Small Note - The problem with link.rpartition('//')[-1] in your code is that you are trying to match // and not /. So remove the extra / as in link.rpartition('/')[-1].



Related Topics



Leave a reply



Submit