例如,我有一个像这样的字符串
this is test string1
this is another test string2
this is another another test string3
我需要按空格分割字符串,然后将除最后两个元素之外的所有元素都加入。所以输出应该像这样
this is
this is another
this is another another
答案 0 :(得分:2)
Regexp_Replace()
应该在这里完成工作:
regexp_replace(yourcolumn, ' [^ ]* [^ ]*$','')
SQLFiddle of this in action(Oracle今天不在sqlfiddle上工作,所以这是postgres;但是他们对regexp_replace的实现几乎是相同的,并且在此示例中是完全相同的)
CREATE TABLE test(f1 VARCHAR(500));
INSERT INTO test VALUES
('this is another another test string3'),
('this is test string1'),
('this is another test string2');
SELECT regexp_replace(f1, ' [^ ]* [^ ]*$','') FROM test;
+-------------------------+
| regexp_replace |
+-------------------------+
| this is another another |
| this is |
| this is another |
+-------------------------+
这里' [^ ]* [^ ]*$'
的正则表达式字符串表示要查找一个空格,后跟任意数量的非空格字符[^ ]*
,然后是另一个空格,然后是任意数量的非空格字符{{1} },然后是字符串[^ ]*
的末尾,我们仅将其替换为$
。
答案 1 :(得分:1)
另一种方法可能是不使用正则表达式,键入较长但执行速度更快;这主要取决于您的需求。
如果输入的字符串少于3个记号,该怎么办还不清楚,所以这是一种处理不同需求的方法:
select str,
case when instr(str, ' ', 1, 2) != 0 then
substr(str, 1, instr(str, ' ', -1, 2)-1)
else
str
end as res1,
substr(str, 1, instr(str, ' ', -1, 2)-1) as res2
from (
select 'this' str from dual union all
select 'this is' str from dual union all
select 'this is test' str from dual union all
select 'this is test string1' str from dual union all
select 'this is another test string2' str from dual union all
select 'this is another another test string3' str from dual
)
STR RES1 RES2
------------------------------------ ------------------------------------ ------------------------------------
this this
this is this is
this is test this this
this is test string1 this is this is
this is another test string2 this is another this is another
this is another another test string3 this is another another this is another another