我有一个字母数字字符串列表,其中包括两个特殊字符
+
和-
。如下所示,输入代表我们公司产品的部件号。我想提取各个组件作为输出。大约有 45,000 种产品,下面的数据是部件号的示例。如何解析此字符串以区分 +
和 -
并提供正确的输出?
我不确定如何区分
-
指示的范围和 +
指示的加法。
创建程序:
DELIMITER //
CREATE PROCEDURE ConvertRangesToList(input_string VARCHAR(255))
BEGIN
DECLARE output_list VARCHAR(255) DEFAULT '';
DECLARE current_part VARCHAR(255);
DECLARE range_start INT;
DECLARE range_end INT;
DECLARE range_separator_pos INT;
DECLARE plus_separator_pos INT;
DECLARE current_number INT;
DECLARE delimiter_pos INT;
-- Replace '+' with ','
SET input_string = REPLACE(input_string, '+', ',');
-- Add a comma at the end to ensure the last number is processed
SET input_string = CONCAT(input_string, ',');
-- Process each part of the input string
WHILE LENGTH(input_string) > 0 DO
-- Find the position of the next comma delimiter
SET delimiter_pos = INSTR(input_string, ',');
-- Extract the current part
SET current_part = TRIM(SUBSTRING(input_string, 1, delimiter_pos - 1));
-- Remove the processed part from the input string
SET input_string = SUBSTRING(input_string, delimiter_pos + 1);
-- Find the position of the range separator '-'
SET range_separator_pos = INSTR(current_part, '-');
IF range_separator_pos > 0 THEN
-- If a range separator is found
SET range_start = CAST(SUBSTRING_INDEX(current_part, '-', 1) AS UNSIGNED);
SET range_end = CAST(SUBSTRING_INDEX(current_part, '-', -1) AS UNSIGNED);
-- Append the range to the output list
WHILE range_start <= range_end DO
SET output_list = CONCAT(output_list, IF(output_list = '', '', ','), range_start);
SET range_start = range_start + 1;
END WHILE;
ELSE
-- If no range separator is found, it's a single number
SET current_number = CAST(current_part AS UNSIGNED);
SET output_list = CONCAT(output_list, IF(output_list = '', '', ','), current_number);
END IF;
END WHILE;
SELECT output_list AS Output;
END//
DELIMITER ;
并称其为:
CALL ConvertRangesToList('1-12+20');