1

I have this:

Dr. LeBron Jordan
John Bon Jovi

I would like this:

Dr. Jordan
John Jovi

How do I come about it? I think it's regexp_replace.

Thanks for looking. Any help is much appreciated.

4

3 回答 3

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
于 2015-04-03T16:27:33.107 回答
0

如果只有两个词,它会返回那个。(“Lebron Jordan”将返回“Lebron Jordan”)

如果是三个字,则取出中间的字(“Dr. LeBron Jordan”会返回“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
于 2015-04-03T15:12:51.913 回答
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

于 2015-04-03T15:33:44.327 回答