We can find the index of the first occurrence of a given substring in MySQL using the INSTR()
function as follows.
SELECT instr('Have_a_good_day', '_') AS index_position
It would display 5
, the first occurrence of the specified substring which is in this case an underscore _
.
I need to obtain the last occurrence of a given character (or a substring) something like the Java lastIndexOf(String str)
method of the String class but I can't find any built-in function in MySQL.
Is there any built-in functionality to achieve this in MySQL?
While the above codes work successfully for a single character, they failed when I used them to find the last occurrence of a substring. I therefore recommend the code below for this task:
This should return 17
I think you can use substring_index in this way:
-1 will start at the end of the string.
Combo of reverse/indexof?
breaking it down, given your
Have_a_good_day
:@Marc B was close. In MySQL, following statement returns 12:
Anticipating a possible use of the value, the following statement extracts the left part of the string before the last underscore(i.e., _):
The result is "first_middle". If you want to include the delimiter, use:
It would be nice if they enhanced LOCATE to have an option to start the search from the right.
If you want the right part of the string after the last space a better solution is:
This returns "last".
If you don't want the overhead of REVERSE use the following:
I found this as a nice trick to do it:
This will return the index of the last occurrence (=12). Basically you search for the right part of the string after the last delimiter and then search for the position of this substring in the whole string, which gets you the position :)
If you would like to get the substring to the left of this you can use: