[英]Oracle Regex grabbing value from key value pair in a string
Consider the following column row:考虑以下列行:
col
-------------------------
'{"day":"8","every":"2"}'
I am trying to get 8 from this string using regular expression to figure out the day.我正在尝试使用正则表达式从这个字符串中获取 8 来计算日期。
so far I have:到目前为止我有:
SELECT
regexp_replace(col, '{"day":[^0-9]', '') as "day"
FROM
mytable;
This gives me:这给了我:
day
---------------
8","every":"2"}
I am having trouble figuring out how to filter out the rest of the string from the first number forward.我无法弄清楚如何从第一个数字向前过滤掉字符串的其余部分。 In my example I just want the number 8 for this row.
在我的示例中,我只想要这一行的数字 8。
When you are lucky enough to use Oracle 12c Release 1 (12.1.0.2) or later, do take a look at JSON_VALUE如果您有幸使用 Oracle 12c 第 1 版 (12.1.0.2) 或更高版本,请查看JSON_VALUE
WITH t (s)
AS (
SELECT '{"day":"8","every":"2"}'
FROM DUAL
)
SELECT JSON_VALUE(s, '$.day' ) AS day
, JSON_VALUE(s, '$.every') AS every
FROM t;
DAY EVERY
--- -----
8 2
How about this?这个怎么样?
SELECT
regexp_replace(col, '{"day":"([0-9]+).*', '\1') as "day"
FROM
mytable;
If you don't have access to JSON_VALUE()
then I would recommend the following regex unless you always know the position of the day
key in the JSON string:如果您无权访问
JSON_VALUE()
那么我建议使用以下正则表达式,除非您始终知道 JSON 字符串中day
键的位置:
SELECT REGEXP_REPLACE(col, '^.*"day":"(\d+)".*$', '\1') AS day
FROM mytable;
This will replace the entire string (assuming it matches!) with the contents of the first capturing group (enclosed in parentheses: (\\d+)
).这将用第一个捕获组的内容(括在括号中:
(\\d+)
)替换整个字符串(假设它匹配!)。 \\d
indicates a digit 0-9
. \\d
表示数字0-9
。 If you want to return NULL values as well, you can replace \\d+
with \\d*
.如果您还想返回 NULL 值,您可以将
\\d+
替换为\\d*
。 If negative or non-numeric values are possible, then I would recommend the following:如果可能出现负值或非数字值,那么我会推荐以下内容:
SELECT REGEXP_REPLACE(col, '^.*"day":"([^"]*)".*$', '\1') AS day
FROM mytable;
This will return whatever characters that might be contained in the day
key.这将返回
day
键中可能包含的任何字符。
FYI, once you have the value, numeric or non-, you can convert it to a number safely by using TO_NUMBER()
along with REGEXP_SUBSTR()
:仅供参考,一旦您拥有数值,数字或非数值,您就可以使用
TO_NUMBER()
和REGEXP_SUBSTR()
将其安全地转换为数字:
SELECT COALESCE( TO_NUMBER( REGEXP_SUBSTR( REGEXP_REPLACE( col, '^.*"day":"[^"]*".*$', '\1' ), '\d+' ) ), 0 ) AS day
FROM mytable;
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.