如何从字符串的开头删除数字和特殊字符?
How to remove digits and special characters from the beginning of a string?
比如我有
'234 - ? Hi there'
结果应该是:
'Hi there'
对于 oracle,您有 regexp_replace
函数。因此,您可以执行以下操作来替换字符串开头的非字母字符:
select regexp_replace('24 Hi','^([^a-zA-Z]*)','') from dual
^([^a-zA-Z]*)
中的第一个^
是匹配字符串的开头。第二个^
是匹配任何非字母字符。
使用此函数删除数字和特殊符号。
CREATE function [dbo].[RemoveNumericandSpecialSymbolValue](@str varchar(500))
returns varchar(500)
begin
declare @text int
set @text=0
while 1=1
begin
set @text= patindex('%[^a-z .]%',@str)
if @text <> 0
begin
set @str = replace(@str,substring(@str,@text,1),'')
end
else break;
end
return @str
end
示例:
select dbo.RemoveNumericandSpecialSymbolValue('234 - ? Hi there')
在 Oracle 中您可以使用 REGEXP_REPLACE()
。我建议使用与已接受答案中的正则表达式略有不同的正则表达式;没有理由对可以为零宽度的图案进行任何替换。此外,括号是不必要的,因为您不需要捕获一个组:
SELECT REGEXP_REPLACE(my_column, '^[^A-Za-z]+') FROM my_table;
我们也可以排除 REGEXP_REPLACE
的第三个参数,因为在 Oracle 中,NULL 和空字符串是等价的。 Oracle 中的另一种选择是使用 POSIX 字符 class [:alpha:]
:
SELECT REGEXP_REPLACE(my_column, '^[^[:alpha:]]+')
FROM my_table;
Please see the SQL Fiddle here. You can read more about POSIX character classes here.
比如我有
'234 - ? Hi there'
结果应该是:
'Hi there'
对于 oracle,您有 regexp_replace
函数。因此,您可以执行以下操作来替换字符串开头的非字母字符:
select regexp_replace('24 Hi','^([^a-zA-Z]*)','') from dual
^([^a-zA-Z]*)
中的第一个^
是匹配字符串的开头。第二个^
是匹配任何非字母字符。
使用此函数删除数字和特殊符号。
CREATE function [dbo].[RemoveNumericandSpecialSymbolValue](@str varchar(500))
returns varchar(500)
begin
declare @text int
set @text=0
while 1=1
begin
set @text= patindex('%[^a-z .]%',@str)
if @text <> 0
begin
set @str = replace(@str,substring(@str,@text,1),'')
end
else break;
end
return @str
end
示例:
select dbo.RemoveNumericandSpecialSymbolValue('234 - ? Hi there')
在 Oracle 中您可以使用 REGEXP_REPLACE()
。我建议使用与已接受答案中的正则表达式略有不同的正则表达式;没有理由对可以为零宽度的图案进行任何替换。此外,括号是不必要的,因为您不需要捕获一个组:
SELECT REGEXP_REPLACE(my_column, '^[^A-Za-z]+') FROM my_table;
我们也可以排除 REGEXP_REPLACE
的第三个参数,因为在 Oracle 中,NULL 和空字符串是等价的。 Oracle 中的另一种选择是使用 POSIX 字符 class [:alpha:]
:
SELECT REGEXP_REPLACE(my_column, '^[^[:alpha:]]+')
FROM my_table;
Please see the SQL Fiddle here. You can read more about POSIX character classes here.