Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last index of a substring in SQLite?

Tags:

I have a string in the table: http://www.foo.com/hello/bar/baz and I want to get everything that comes after the last '/' (in this case the string 'baz').

I can do substr(str, lastIndexOf(str, '/')), but I dont know how to get the lastIndexOf in SQLite.

like image 916
chacham15 Avatar asked Jan 27 '14 18:01

chacham15


People also ask

How to search substring in SQLite?

You can use LIKE , but it gets really slow if the pattern you're searching for starts with '%' -- i.e., if the substring you're looking for isn't necessarily at the beginning of the field. If you need to do such searches, consider using FTS3, which makes full-text searching considerably more efficient.

What are the three arguments for the substr () function in SQLite?

SQLite substr() returns the specified number of characters from a particular position of a given string. A string from which a substring is to be returned. An integer indicating a string position within the string X. An integer indicating a number of characters to be returned.

How do I reverse a string in SQLite?

Using a common table expression it is possible to reverse a string in SQLite. WITH reverse(i, c) AS ( values(-1, '') UNION ALL SELECT i-1, substr('dlrow olleh', i, 1) AS r FROM reverse WHERE r!= '' ) SELECT group_concat(c, '') AS reversed FROM reverse; Returns hello world .


2 Answers

select replace(str, rtrim(str, replace(str, '/', '')), '') from table;

Step-by-step explanation. For example, we have the string:

/storage/udisk/1200 Mics/[2002] 1200 Micrograms/1200 Mics - 03 - Mescaline.mp3

The replace(str, '/', '') removes / chars from str so we will have:

storageudisk1200 Mics[2002] 1200 Micrograms1200 Mics - 06 - Ecstasy.mp3

Let's call this noslashes. Next we use rtrim(str, noslashes), which will remove all chars that appear in noslashes, starting from the right. Because noslashes contains everything in the string except /, this will trim from the right until it finds the / char. This way we found our parent dir:

/storage/udisk/1200 Mics/[2002] 1200 Micrograms/

Now we remove the parent path name from the file path using replace and we have just the filename

1200 Mics - 03 - Mescaline.mp3

like image 70
ungalcrys Avatar answered Sep 30 '22 07:09

ungalcrys


There are limits to sqlite core functions' expressive power. For a known maximum number of / characters, this can be accomplished by a series of nested substr() and instr() calls, removing parts of the string to the next / at a time, but that's not too elegant.

You should really do it in your programming language instead.

like image 27
laalto Avatar answered Sep 30 '22 07:09

laalto