如何在 Oracle 中解析字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6432026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse a string in Oracle?
提问by ed1t
How can I parse the value of "request" in the following string in Oracle?
如何在 Oracle 中解析以下字符串中“请求”的值?
<!-- accountId="123" activity="add" request="add user" -->
<!-- accountId="123" activity="add" request="add user" -->
The size and the position of the request is random.
请求的大小和位置是随机的。
回答by Craig
You can use regular expressions to find this:
您可以使用正则表达式来查找:
regexp_replace(str, '.*request="([^"]*)".*', '')
回答by Oleg Pavliv
Use INSTR(givenstring, stringchartosearch,start_position)
to find the position of 'request="' and to find the position of the closing '"'.
使用INSTR(givenstring, stringchartosearch,start_position)
找到的位置“的要求=“”,并找到该关闭的位置'”。
Then use substr(string, starting_position, length)
.
然后使用substr(string, starting_position, length)
.
回答by cwallenpoole
You'd use a combination of instr
and substr
THIS EXAMPLE IS FOR EXAMPLE PURPOSES ONLY. DO NOT USE IT IN PRODUCTION CODE AS IT IS NOT VERY CLEAN.
本示例仅用于示例目的。不要在生产代码中使用它,因为它不是很干净。
substr(my_str,
-- find request=" then get index of next char.
instr(my_str, 'request="') + 9,
-- This is the second " after request. It does not allow for escapes
instr(substr(my_str,instr(my_str, 'request="')), 2))
回答by Joel Slowik
Below is my tested variations from cwallenpoole and Craig. For the regexp - note that if "request=" does not exist, the result will be the entire string. user349433 was partly there too, a space before "request=" in the search works just as well:
以下是我从 cwallenpoole 和 Craig 测试的变体。对于正则表达式 - 请注意,如果“request=”不存在,则结果将是整个字符串。user349433 也部分存在,搜索中“request=”之前的空格也同样有效:
SET serveroutput ON
DECLARE
l_string VARCHAR2(100) := '<!-- accountId="123" activity="add" request="add user" -->';
l_result_from_substr VARCHAR2(50);
l_result_from_regexp VARCHAR2(50);
BEGIN
SELECT SUBSTR(l_string, instr(l_string, 'request="') + 9, instr(SUBSTR(l_string,instr(l_string, 'request="')), '"', 2)-1),
regexp_replace(l_string, '.* request="([^"]*)".*', '')
INTO l_result_from_substr,
l_result_from_regexp
FROM dual;
dbms_output.put_line('Result from substr: '||l_result_from_substr);
dbms_output.put_line('Result from regexp: '||l_result_from_regexp);
END;
/
回答by Perrault Jean-Paul
Please note the equal sign "=" does not necessarily have to come immediately after the request variable in the assignment. As such, it is not entirely correct to search for "request=". You should create a basic finite state machine using INSTR to first find "request", then find "=", ...
请注意等号“=”不一定要紧跟在赋值中的请求变量之后。因此,搜索“request=”并不完全正确。您应该使用 INSTR 创建一个基本的有限状态机,首先找到“请求”,然后找到“=”,...