I'm still learning regexp in oracle and stuck with below error. Below is my sample code
SELECT DISTINCT COALESCE(TO_NUMBER(regexp_substr(USERNAME, '[^.]+', 1, 2)), ID) ID ,
COALESCE(regexp_substr(USERNAME, '[^.]+', 1, 1), USERNAME) AS USERNAME
FROM logs;
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause: The specified number was invalid.
*Action: Specify a valid number.
Table Data
Username ID
Ravi.1234 1234
Krishna.12345 12345
Ravi.Krishna.1234567 1234567
R.Krishna.987 987
Ravi.K.567890 567890
R.Krish 123
Ravi 456
Expected Output
ID Username
1234 Ravi
12345 Krishna
1234567 Ravi.Krishna
987 R.Krishna
567890 Ravi.K
How to reframe the query to get the output needed. Can substr be used instead of regexp will it give desired output? This is used in oracle database not in sql. Thanks in advance.
If I understood your assignment correctly (see my comments under your question), here is how you can do this with standard string functions and conditions:
In the
LIKE
condition in theWHERE
clause, % is a wildcard for "any string of any length, including zero"; that must be followed by a literal dot and then by the ID, and that must be the whole USERNAME string. Inselect
,instr(username, '.', -1)
finds the position of the "first" dot inusername
, but counting from the end and moving left - that is what the minus sign means.With regular expression functions and conditions:
The sixth argument to
regexp_substr
means "the first substring enclosed in parentheses" (first "capture group" is the technical term).