简体   繁体   English

使用正则表达式将一列拆分为多列

[英]Using regular expressions to split one column into multiple columns

I have a table and some data: 我有一张桌子和一些数据:

-- Table
CREATE TABLE IF NOT EXISTS `myTable` (
  `myColumn` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Data
INSERT INTO `myTable` (`myColumn`) VALUES
('AAA BBB CCC'),
('AA BB CCCC'),
('BBB CC AAAA'),
('C AAA BBB'),
('CCC AA BBB');

I would like to run a SELECT query that return 3 columns. 我想运行一个返回3列的SELECT查询。

The columns should be called A , B , and C . 这些列应称为ABC

The result should look something like: 结果应类似于:

+------+-----+------+
| A    | B   | C    |
+------+-----+------+
| AAA  | BBB | CCC  |
| AA   | BB  | CCCC |
| AAAA | BBB | CC   |
| AAA  | BBB | C    |
| AA   | BBB | CCC  |
+------+-----+------+

I have three regular expressions which, by using them all, can match all data: 我有三个正则表达式,通过全部使用它们,可以匹配所有数据:

^([A]+) ([B]+) ([C]+)$
^([B]+) ([C]+) ([A]+)$
^([C]+) ([A]+) ([B]+)$

Is it possible to use these regular expressions to produce such a result? 是否可以使用这些正则表达式产生这样的结果?

If so, would appreciate an example, even if only for a subset of the problem. 如果是这样,请欣赏一个示例,即使仅针对问题的一个子集。

This can't be done using regexes in MySQL. 使用MySQL中的正则表达式无法做到这一点。 Unfortunately, MySQL support regexes only as a boolean condition (notably in where clauses), but not to extract nor alter the content of a string. 不幸的是,MySQL仅将正则表达式作为布尔条件来支持(特别是在where子句中),而不能提取或更改字符串的内容。

You may however achieve what you described entirely from a MySQL query, using substring_index . 但是,您可以使用substring_index从MySQL查询中完全实现您描述的内容。 Here is an example usage for your scenario. 这是您的方案的示例用法。

SELECT substring_index(substring_index(myColumn, ' ', 1), ' ', -1) AS `A`, 
       substring_index(substring_index(myColumn, ' ', 2), ' ', -1) AS `B`,
       substring_index(                myColumn         , ' ', -1) AS `C`
  FROM ...  

Alternatively, if you must absolutely use regexes, then you might pipe MySQL's output to some regex engine. 另外,如果您必须绝对使用正则表达式,则可以将MySQL的输出通过管道传递给某些正则表达式引擎。 Ask me if you need more info about this strategy. 询问我是否需要有关此策略的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM