简体   繁体   中英

Regex in Oracle SQL Query - numbers and periods only

In an Oracle SQL query there is a field with the following content (example):

{"ID Card": 0.29333333333333333} or {"Speedtest": 0.8166666666666667}

Can I use RegEx, for example, to output the field in the query so that only the numbers and the period remain?

Example:

Select ID, CREATEDFORMAT, INSERT_TS, regexp_substr(SCORE, '[^0-9]') xSCORE FROM MYTABLE

But with the [^ 0-9] I only have the numbers without a point.

If you are using Oracle Database 12.1.0.2 or higher and the number you are trying to parse out is always in a JSON object, you can use the JSON_VALUE function to pull the information out.

Query

WITH
    sample_data
    AS
        (SELECT '{"ID Card": 0.29333333333333333}' AS sample_val FROM DUAL
         UNION ALL
         SELECT '{"Speedtest": 0.8166666666666667}' FROM DUAL)
SELECT s.sample_val, json_value (s.sample_val, '$.*') AS number_val
  FROM sample_data s;

Result

                          SAMPLE_VAL             NUMBER_VAL
____________________________________ ______________________
{"ID Card": 0.29333333333333333}        0.29333333333333333
{"Speedtest": 0.8166666666666667}        0.8166666666666667

Use

REGEXP_SUBSTR(SCORE, '[-+]?[0-9]*\.?[0-9]+')

See proof

Explanation

--------------------------------------------------------------------------------
  [-+]?                    any character of: '-', '+' (optional
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  [0-9]*                   any character of: '0' to '9' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \.?                      '.' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  [0-9]+                   any character of: '0' to '9' (1 or more
                           times (matching the most amount possible))

use: REGEXP_SUBSTR (s.sample_val, '[+-]?[0-9]+[\\.]?[0-9]+')

see this demo: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=76c2b3be1d7d266f217d6b0541478c17

result:

SAMPLE_VAL                          NUMBER_VAL
----------------------------------  --------------------
{"ID Card": 0.29333333333333333}    0.29333333333333333
{"Speedtest": 0.8166666666666667}   0.8166666666666667
{"texts": 12.3456}                  12.3456
{"texts": -65}                      -65

This is a change to @Ryszard Czech's post.

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