如何将字符添加到字符串中的特定索引

时间:2019-01-15 14:21:42

标签: mysql

我有一个数据库,该数据库的电子邮件地址总计15个字符。

有些字符长14个字符,它们的共同点相同,它们在第3个索引处的名称中缺少'aa-001@test.me'

我在编号上也遇到了类似的问题,但是很容易解决,因为我必须将0推到第一个索引。

我的预期结果应该是将'aa-0001@test.me'更改为x <- "201805" x <- paste0(x, "01") x y <- format(as.Date(x, format = "%Y%m%d"), "%Y-%m-%d") substr(y, 1, 7) [1] "20180501" [1] "2018-05"

1 个答案:

答案 0 :(得分:0)

要在具有14个字符的0中添加email作为第四字符,您可以简单地使用SUBSTR

SELECT CONCAT(SUBSTR(email, 1, 3), '0', SUBSTR(email, 4))
FROM mytable
WHERE LENGTH(email) = 14

另一种解决方案是使用REGEXP_REPLACE,其正则表达式仅与14个字符的电子邮件匹配;这样可以避免使用WHERE子句,因为与模式不匹配的电子邮件将原封不动地返回:

SELECT REGEXP_REPLACE(email, '^(.{3})(.{11})$', CONCAT('$1', '0', '$2'))
FROM t

db <>提琴here

 WITH t AS (SELECT 'aa-001@test.me' email UNION SELECT 'bb-0002@test.me')
 SELECT CONCAT(SUBSTR(email, 1, 3), '0', SUBSTR(email, 4))
 FROM t
 WHERE LENGTH(email) = 14

| CONCAT(SUBSTR(email, 1, 3), '0', SUBSTR(email, 4)) |
| :----------------------------------------------------- |
| aa-0001@test.me                                        |


 WITH t AS (SELECT 'aa-001@test.me' email UNION SELECT 'bb-0002@test.me')
 SELECT REGEXP_REPLACE(email, '^(.{3})(.{11})$', CONCAT('$1', '0', '$2'))
 FROM t

| REGEXP_REPLACE(email, '^(.{3})(.{11})$', CONCAT('$1', '0', '$2')) |
| :---------------------------------------------------------------- |
| aa-0001@test.me                                                   |
| bb-0002@test.me