将字符串中的字符转换为数字固定位置,2|4|6|需要,020406

Convert characters in string to numeric fixed positions ,2|4|6| needs to be ,020406

我有很多文件需要修改才能导入 cpanel,mysql。数字模式布局为 ,2|5|7|31|37|43|5 要将文件导入正确的字段,数据的格式需要为 02050731374305

是只使用记事本++编辑所有文件更好,还是有更好的方法导入这些数据? Mysql 字段只允许使用数字,并且在此特定文件中限制为 14 位数字。

我拥有的文件非常相似,但长度不同。文件中总共只有 2 列要导入 mysql、cpanel.

reg 表达式可能有效,但我一直在发现替换错误,因为它正在选取行中的其他数字并更改数据。

这是一个使用 awk 的快速解决方案:

echo "2|5|7|31|37|43|5" | awk -F'|' '{printf("%02d%02d%02d%02d%02d%02d%02d\n", , , , , , , )}'
02050731374305

正如我所说的一个函数,它打破字符串并构建新的字符串,将帮助您

DELIMITER //
CREATE DEFINER=`root`@`localhost` FUNCTION `new_function`(fullstr TEXT, delim char(1)) RETURNS char(16) CHARSET utf8mb4
    DETERMINISTIC
BEGIN
DECLARE inipos INTEGER;
DECLARE endpos INTEGER;
DECLARE maxlen INTEGER;
DECLARE item VARCHAR(100);

SET inipos = 1;
SET @temptxt = '';
SET fullstr = CONCAT(fullstr,delim);
SET maxlen = LENGTH(fullstr) ;

REPEAT
    SET endpos = LOCATE(delim, fullstr, inipos);
    SET item =  SUBSTR(fullstr, inipos, endpos - inipos);

    IF item <> '' AND item IS NOT NULL THEN           
        SET @temptxt = CONCAT(@temptxt,LPAD(item,2,'0'));
    END IF;
    SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
RETURN @temptxt;
END/7
DELIMITER ;

所以你可以

SELECT new_function('2|5|7|31|37|43|5','|')

并获得

02050731374305

这可以使用 Notepad++ 轻松完成,利用 lookaround 的强大功能。

这将在每个数字前单独添加一个零,它适用于任意数量的值:

  • Ctrl+H
  • 查找内容:(?<!\d)(?=\d(?!\d))
  • 替换为:0
  • 检查 环绕
  • 检查 正则表达式
  • 全部替换

解释:

(?<!            # negative lookbehind, make sure we haven't before:
  \d              # a digit
)               # end lookbehind
(?=             # positive lookahead, make sure we have after:
  \d              # digit
  (?!\d)          # not followed by another digit
)               # end lookahead

截图(之前):

截图(后):