Split text by symbol: Difference between revisions

From LemonWiki共筆
Jump to navigation Jump to search
Line 3: Line 3:
== Approaches ==
== Approaches ==
list of equivalent approaches to split text by symbol
list of equivalent approaches to split text by symbol
* Excel: (1) LEFT, RIGHT, FIND, LEN (2) MOD, FIND, LEN
* PHP: [http://php.net/explode explode] function
* PHP: [http://php.net/explode explode] function
* MySQL: [http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php MySQL SUBSTRING_INDEX() function - w3resource]
* MySQL: [http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php MySQL SUBSTRING_INDEX() function - w3resource]
* Excel: (1) LEFT, RIGHT, FIND, LEN (2) MOD, FIND, LEN


== Example ==
== Example ==

Revision as of 13:47, 24 April 2015

Split text by symbol (another string, also called delimiter or separator)

Approaches

list of equivalent approaches to split text by symbol

Example

Task: Split 25.040215, 121.512532 by the comma ( , )

Expected output:

  • 25.040215
  • 121.512532

MySQL Approach

  1. to get the first string ( 25.040215 ): SELECT TRIM(SUBSTRING_INDEX('25.040215, 121.512532' ,',', 1))
  2. to get the second string ( 121.512532 ): SELECT TRIM(SUBSTRING_INDEX('25.040215, 121.512532' ,',', -1))

Live demo on SQL Fiddle

CREATE TABLE tbl(str varchar(50));
INSERT INTO tbl VALUES('25.040215, 121.512532');
SELECT TRIM(SUBSTRING_INDEX(str ,',', 1)), TRIM(SUBSTRING_INDEX(str ,',', -1)) FROM tbl;

Excel Approach

A B C
1 25.040215, 121.512532
25.040215
121.512532

If the data is perfect

  1. to get the first string ( 25.040215 ): B1 = MID( A1, 1, FIND("-", A1)-1)
  2. to get the second string ( 121.512532 ): C1 = MID( A1, FIND(",", A1)+1, LEN(A1))

if the data was mixed with empty values. Return empty if the value is empty.

  1. to get the first string ( 25.040215 ): B1 = IF(ISERROR(MID(A1, 1, FIND(",", A1)-1)), "", MID(A1, 1, FIND(",", A1)-1))
  2. to get the second string ( 121.512532 ): C1 = IF(ISERROR(TRIM(MID(A1, FIND(",", A1)+1, LEN(A1)))), "", TRIM(MID(A1, FIND(",", A1)+1, LEN(A1)))


online demo (allow to edit)