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

Removing one word in a string (or between two white spaces)

我有这个:

Dr. LeBron Jordan
John Bon Jovi

我想要这个:

Dr. Jordan
John Jovi

我是怎么做到的?我认为是 regexp_replace.

感谢观看。 非常感谢任何帮助。

如果只有两个字,它会return那个。 ("Lebron Jordan" 将 return "Lebron Jordan")

如果是三个字,就把中间的字去掉("Dr. LeBron Jordan"会return"Dr. 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

在 SQL 服务器中尝试以下单个语句:

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

我试过同样的例子,请参考 fiddle link : http://sqlfiddle.com/#!4/74986/31

这是您提到的使用 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, '^([^ ]*) .* ([^ ]*)$', ' ') 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' 表示 return 记住第 1 组,然后是 space,然后是记住的第 2 组。

如果找不到模式,则return编辑原始字符串。这可以通过用方括号包围 returned 组并再次 运行 来看出:

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

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