For example, if the existing string "[] aseabcd [12345] ddxabcdsx []" is to be intercepted, the content between "abcd [" and "first"] "after" abcd ["" 12345 ", of course, the content length is not fixed, it can be "123456" or other strings.
When he asked me, I first thought about indexOf. Later I checked and found that there was no indexOf but locate in mysql.
After more than half an hour of trying, we 'd better help him achieve this effect.
Copy codeThe Code is as follows:
Create procedure sp_str
(
IN p_str VARCHAR (50),/* original string */
IN p_begin_str VARCHAR (50),/* Start string to be matched */
IN p_end_str VARCHAR (50)/* end string to be matched */
OUT p_result VARCHAR (50)/* return result */
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT''
BEGIN
DECLARE m_len int default 0;
DECLARE m_index int default 0;
/* Calculate the index position of the first matching string */
Select locate (p_begin_str, p_str) + char_length (p_begin_str) into m_index;
/* Calculate the length of the first matching string */
Select locate (p_end_str, p_str, m_index) into m_len;
Select SUBSTRING (p_str, m_index, m_len-m_index) INTO p_result;
END;
Run:
CALL sp_str ('[] abcd [12345] aa [] ss', 'abcd [', ']', @ result );
Return Value @ result is 12345
Call sp_str ('[] abcd [sdww] aa [] ss', 'abcd [', ']', @ result );
Return Value @ result: sdww
If you do not need stored procedures, you can directly write SQL statements:
For example:
Copy codeThe Code is as follows:
Select SUBSTRING (
'] Abcd [12345] 111 []',
Locate ('abcd [','] abcd [12345] 111 [] ') + CHAR_LENGTH ('abcd ['),
Locate (']', '] abcd [12345] 111 []', CHAR_LENGTH ('abcd ['))-
(Select locate ('abc [','] abcd [12345] 111 [] ') + CHAR_LENGTH ('abcd ['))
)
Returns 12345
Mysql functions:
CHAR_LENGTH (str)
Returns the length of the str string.
LOCATE (substr, str)
POSITION (substr IN str)
Returns the position of the substring substr In the first occurrence of the str. If the substring is not in the str, the return value is 0.
Mysql> select LOCATE ('bar', 'foobarbar ');
-> 4
Mysql> select LOCATE ('xbar', 'foobar ');
-> 0
This function is multi-byte reliable. LOCATE (substr, str, pos)
Returns the position of the substring substr at the first occurrence of the substring, starting from the position pos. If substr is not in str, 0 is returned.
Mysql> select LOCATE ('bar', 'foobarbarbar ', 5 );
-> 7
This function is multi-byte reliable.
SUBSTRING (str, pos, len)
SUBSTRING (str FROM pos FOR len)
MID (str, pos, len)
Returns a substring of len characters from the str string, starting from the position pos. The variant form of FROM is ANSI SQL92 syntax.
Mysql> select SUBSTRING ('quadratically ', 5, 6 );
-> 'Ratica'
This function is multi-byte reliable.
SUBSTRING (str, pos)