我正在使用Firebird 2.1。
我有一个作业序号,它可能有1或2个alpha字符,然后是4或5个数字,然后可能是一个前缀,带有1个alpha字符和2个数字。
我要提取中间的4-5位数。
我试着查找数字char,但是它返回0:
POSITION('%[0-9]%',JOBHEADER.ORDERNUMBER,1) AS "FIRST NUMBER"
我不确定是否可以在POSITION函数中使用通配符。我想我可以尝试检查第二个或第三个字符的数字,但我真的需要外卡功能,然后找到下一个阿尔法后,我找到了第一个数字的位置。或者还有另一种方法来提取数字。
我发现了一些类似的东西:
CASE WHEN SUBSTRING(ordernumber FROM 2 FOR 5) SIMILAR TO '[0-9]+'
THEN SUBSTRING(ordernumber FROM 2 FOR 5)
ELSE SUBSTRING(ordernumber FROM 3 FOR 5)
END as PROJECTNUMBER但是,随着数字可能从前5个字符开始,if/case语句开始变得相当大。
发布于 2020-03-30 13:08:45
不,你不能用POSITION做这个。位置搜索给定字符串中的确切子字符串。但是,使用Firebird 3,可以使用带有正则表达式的SUBSTRING提取值,例如:
substring(ordernumber similar '%#"[[:DIGIT:]]+#"%' escape '#')正则表达式必须覆盖整个字符串,而#"则包含要提取的术语( #是显式定义的转义符号)。您可能需要使用更复杂的模式,如[^[:DIGIT:]]*#"[[:DIGIT:]]+#"([^[:DIGIT:]]%)?,以避免贪婪的边缘情况。
如果您知道模式总是1或2 alpha,4或5位您想要提取,可能后面跟着1α和2个数字,您也可以使用[[:ALPHA:]]{1,2}#"[[:DIGIT:]]{4,5}#"([[:ALPHA:]][[:DIGIT:]]{1,2})?。如果模式不匹配,则返回null。
另请参阅:
请注意,Firebird支持的SQL标准正则表达式语法有点奇怪,而且功能不如其他语言中常见的正则表达式。
使用PSQL
若要使用PSQL解决此问题,请在Firebird 2.1下使用以下内容:
create or alter procedure extract_number(input_value varchar(50))
returns (output_value bigint)
as
declare char_position integer = 0;
declare number_string varchar(20) = '';
declare current_char char(1);
begin
while (char_position < char_length(input_value)) do
begin
char_position = char_position + 1;
current_char = substring(input_value from char_position for 1);
if ('0' <= current_char and current_char <= '9') then
begin
number_string = number_string || current_char;
end
else if (char_length(number_string) > 0) then
begin
-- switching from numeric to non-numeric, found first number occurrence in string
leave;
end
end
output_value = iif(char_length(number_string) > 0, cast(number_string as bigint), null);
endhttps://stackoverflow.com/questions/60921758
复制相似问题