简体   繁体   中英

Oracle SQL - select parts of a string

How can I select abcdef.txt from the following string?

abcdef.123.txt

I only know how to select abcdef by doing select substr('abcdef.123.txt',1,6) from dual;

You can using || for concat and substr -3 for right part

select substr('abcdef.123.txt',1,6)  || '.' ||substr('abcdef.123.txt',-3) from dual;

or avoiding a concat (like suggested by Luc M)

select substr('abcdef.123.txt',1,7)   || substr('abcdef.123.txt',-3) from dual;

A general solution, assuming the input string has exactly two periods . and you want to extract the first and third tokens, separated by one . The length of the "tokens" in the input string can be arbitrary (including zero!) and they can contain any characters other than .

select regexp_replace('abcde.123.xyz', '([^.]*).([^.]*).([^.]*)', '\1.\3') as result
  from dual;

RESULT
---------
abcde.xyz

Explanation:

  • [ ] means match any of the characters between brackets .
  • ^ means do NOT match the characters in the brackets - so...
  • [^.] means match any character OTHER THAN .
  • * means match zero or more occurrences, as many as possible ( "greedy" match)
  • ( ... ) is called a subexpression ... see below
  • '\\1.\\3 means replace the original string with the first subexpression, followed by . , followed by the THIRD subexpression .

Replace the substring of anything surrounded by dots (inclusive) with a single dot. No dependence on lengths of components of the string:

SQL> select regexp_replace('abcdef.123.txt', '\..*\.', '.') fixed
     from dual;

FIXED
----------
abcdef.txt

SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM