删除字符串中的一个单词(或两个空格之间)

时间:2015-04-03 14:24:24

标签: sql oracle plsql regexp-replace

我有这个:

Dr. LeBron Jordan
John Bon Jovi

我想这样:

Dr. Jordan
John Jovi

我该怎么做?我认为它是regexp_replace。

谢谢你的期待。 非常感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

如上所述,这是使用regexp_replace的方法,使用多种形式的名称进行测试。比嵌套的SUBSTR(),INSTR()更强大,但是你需要了解正则表达式,一旦你学会了它,就可以为更复杂的模式提供更多的模式匹配能力:

with tbl as (
  select 'Dr. LeBron Jordan' data from dual
  union
  select 'John Bon Jovi' data from dual
  union
  select 'Yogi Bear' data from dual
  union
  select 'Madonna' data from dual 
  union
  select 'Mr. Henry Cabot Henhouse' data from dual  ) 

select regexp_replace(data, '^([^ ]*) .* ([^ ]*)$', '\1 \2') corrected_string from tbl;

CORRECTED_STRING
----------------
Dr. Jordan
John Jovi
Madonna
Mr. Henhouse
Yogi Bear

正则表达式可以理解为:

^      At the start of the string (anchor the pattern to the start)
(      Start remembered group 1
[^ ]*  Zero or more characters that are not a space
)      End remembered group 1
space  Where followed by a literal space
.      Followed by any character
*      Followed by any number of the previous any character
space  Followed by another literal space
(      Start remembered group 2
[^ ]*  Zero or more characters that are not a space
)      End remembered group 2
$      Where it occurs at the end of the line (anchored to the end)

然后'\ 1 \ 2'表示返回记住的组1,后跟一个空格,然后记住组2。

如果找不到模式,则返回原始字符串。通过用方括号包围返回的组并再次运行可以看出这一点:

...
select regexp_replace(data, '^([^ ]*) .* ([^ ]*)$', '[\1] [\2]')
corrected_string from tbl;

CORRECTED_STRING
[Dr.] [Jordan]
[John] [Jovi]
Madonna
[Mr.] [Henhouse]
Yogi Bear

答案 1 :(得分:0)

如果只有两个单词,它将返回。 (“勒布朗乔丹”将返回“勒布朗乔丹”)

如果是三个字,它将取出中间词(“LeBron Jordan博士”将返回“乔丹博士”)

DECLARE @firstSpace int = 0
DECLARE @secondSpace int = 0
DECLARE @string nvarchar(50) = 'Dr. Lebron Jordan'

SELECT @string = LTRIM(RTRIM(@string))

SELECT @firstSpace = CHARINDEX(' ', @string, 0)
SELECT @secondSpace = CHARINDEX(' ', @string, @firstSpace + 1)

IF @secondSpace = 0
BEGIN
    SELECT @string
END
ELSE
BEGIN
    SELECT SUBSTRING(@string, 0, @firstSpace) + SUBSTRING(@string, @secondSpace, (LEN(@string) - @secondSpace) + 1)
END

答案 2 :(得分:0)

在SQL Server中尝试以下单个语句:

declare @fullname varchar(200)
select @fullname='John Bon Jovi'
select substring(@fullname,1,charindex(' ',@fullname,1)) +  substring(@fullname, charindex(' ',@fullname,charindex(' ',@fullname,1)+1)+1, len(@fullname) - charindex(' ',@fullname,charindex(' ',@fullname,1)))

在Oracle中尝试以下声明

select substr(name,1,INSTR(name,' ', 1, 1)) 
|| substr(name, INSTR(name,' ', 1, 2)+1,length(name) - INSTR(name,' ', 1, 2))from temp

我尝试了同样的例子,请参考小提琴链接:http://sqlfiddle.com/#!4/74986/31