oracle - 如何从oracle中的字符串中仅删除左括号和右括号?

标签 oracle

我有一个像这样的字符串:

(1/8 英寸帽 TBE ASME B1.20.1 (NPT) 外线程 x 内线程 CL400 CU 合金 B152 Gr C10400 水泥衬里)

我需要这样的输出:

1/8 英寸帽 TBE ASME B1.20.1 (NPT) 外线程 x 内线程 CL400 CU 合金 B152 Gr C10400 水泥内衬

即仅删除开头和结尾处的括号,而不是中间的括号。

还有 如果字符串是这样的,要么有起始括号,要么有结束括号

(1/8 英寸帽 TBE ASME B1.20.1 (NPT) 外线程 x 内线程 CL400 CU 合金 B152 Gr C10400 水泥内衬

1/8 英寸盖 TBE ASME B1.20.1 (NPT) 外线程 x 内线程 CL400 CU 合金 B152 Gr C10400 水泥衬里)

然后不要删除括号。

我尝试使用 regexp_replace 但找不到解决方案。 任何帮助都将是值得赞赏的

最佳答案

简单的CASE足以删除前导结尾括号

with txt as (
select '(xxxx)' txt from dual union all
select '(x(x)xx)' txt from dual union all
select '(xxxx' txt from dual union all
select 'xxxx)' txt from dual union all
select 'xxxx' txt from dual)
select txt,
case when txt like '(%)' then 
    substr(txt,2,length(txt)-2)
else
   txt
end as new_txt
from txt

给出

TXT      NEW_TXT
-------- --------
(xxxx)   xxxx     
(x(x)xx) x(x)xx   
(xxxx    (xxxx    
xxxx)    xxxx)    
xxxx     xxxx  

或者,您可以使用REGEXP,如下所示

select 
  txt,
  nvl(
     REGEXP_SUBSTR(txt, '^\((.*)\)$', 1, 1, null, 1),
     txt)
  as txt_new
from txt

正则表达式 '^\((.*)\)$' 强制使用前括号和尾括号,并返回 - 第一组(REGEXP_SUBSTR 的第五个参数)之间的部分。

如果 REGEXP_SUBSTR 返回注释,即表达式未括在括号中,则 NVL 返回原始值。

关于oracle - 如何从oracle中的字符串中仅删除左括号和右括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60558191/

相关文章:

sql - 考虑到动态查询的索引大平面表的最佳方式

java - 使用 Oracle DBMS : No matching username found in Principals 登录 JBOSS

oracle - 从内存中数据源切换到Oracle数据库时,Grails GORM-ArrayIndexOutOfBoundsException

javascript - Apex Oracle - 多个动态操作

oracle - Pandas 和 SQL 炼金术 : Specify Column Data Types

java - 为什么 Eclipse 构建路径中需要 oracle 驱动程序?

sql - 以 Oracle 10g 为中心

java - 在netbeans中连接oracle数据库

oracle - 获取oracle中的上一次出现和下一次出现

sql - 最高/最低 pl/sql