Regular expressions in Oracle 9i
Hello,
Does oracle 9i support regular expressions?
I need to check if a varchar parameter contains only numbers OR letters, otherwise i should return false.
Thanks.
Roger22 wrote:
Hello,
Does oracle 9i support regular expressions?
I need to check if a varchar parameter contains only numbers OR letters, otherwise i should return false.
Thanks.TRANSLATE is helpful to do such a check.
example
WITH testdata AS
(SELECT 'abcdef' txt FROM DUAL UNION ALL
SELECT '1234567' txt FROM DUAL union all
SELECT '0' txt FROM DUAL union all
SELECT '123a4567x00' txt FROM DUAL union all
SELECT '123.4567,00' txt FROM DUAL
select txt,
translate(txt,'a1234567890','a') numbers_removed,
translate(txt,'0abcdefghijklonopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ','0') letters_removed
from testdata;
TXT NUMBERS_REMOVED LETTERS_REMOVED
abcdef abcdef
1234567 1234567
0 0
123a4567x00 ax 123456700
123.4567,00 ., 123.4567,00One idea is to check the result for NULL or to compare the length of similiar expressions.
Problems are usually special chars and how you want to handle that.
Edited by: Sven W. on Aug 11, 2010 11:07 AM
Edited by: Sven W. on Aug 11, 2010 11:07 AM
Similar Messages
-
Hello All,
I come from Perl scripting language background. Perl's regular expressions are rock solid, robust and very fast.
Now I am planning to master Regular Expressions in Oracle.
Could someone please point the correct place to start with it like official Oracle documentation on Regular Expressions, any good book on Regex or may be any online link etc.
Cheers,
Parag
Edited by: Parag Kalra on Dec 19, 2009 11:03 AMHi, Parag,
Look under [R in the index of the SQL language manual|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/index.htm#R]. All the regular expression functions and operators start with "REGEXP", and there are a couple of entries under "regular expressions".
That applies to the Oracle 11 and 10.2 documentation. Regular expressions were hidden in the Oracle 10.1 SQL Language manual; you had to look up some similar function (like REGR_SYY, itself hidden under S for "SQL Functions", and then step through the pages one at a time.
Sorry, I don't know a good tutorial or introduction.
If you find something hopeful, please post a reference here. I think a lot of people would be interrested. -
Regular expressions in oracle 10 g
how to use regular expressions in oracle 10g forms
May be forms related question better answered in forms forum.
Forms -
Regular expression vs oracle text performance
Does anyone have experience with comparig performance of regular expression vs oracle text?
We need to implement a text search on a large volume table, 100K-500K rows.
The select stmt will select from a VL, a view joining 2 tables, B and _TL.
We need to search 2 text columns from this _VL view.
Using regex seems less complex, but the deciding factor is of course performace.
Would oracle text search perform better than regular expression in general?
Thanks,
MargaretHi Dominc,
Thanks, we'll try both...
Would you be able to validate our code to create the multi-table index:
CREATE OR REPLACE PACKAGE requirements_util AS
PROCEDURE concat_columns(i_rowid IN ROWID, io_text IN OUT NOCOPY VARCHAR2);
END requirements_util;
CREATE OR REPLACE PACKAGE BODY requirements_util AS
PROCEDURE concat_columns(i_rowid IN ROWID, io_text IN OUT NOCOPY VARCHAR2)
AS
tl_req pjt_requirements_tl%ROWTYPE;
b_req pjt_requirements_b%ROWTYPE;
CURSOR cur_req_name (i_rqmt_id IN pjt_requirements_tl.rqmt_id%TYPE) IS
SELECT rqmt_name FROM pjt_requirements_tl
WHERE rqmt_id = i_rqmt_id;
PROCEDURE add_piece(i_add_str IN VARCHAR2) IS
lx_too_big EXCEPTION;
PRAGMA EXCEPTION_INIT(lx_too_big, -6502);
BEGIN
io_text := io_text||' '||i_add_str;
EXCEPTION WHEN lx_too_big THEN NULL; -- silently don't add the string.
END add_piece;
BEGIN
BEGIN
SELECT * INTO b_req FROM pjt_requirements_b WHERE ROWID = i_rowid;
EXCEPTION
WHEN NO DATA_FOUND THEN
RETURN;
END;
add_piece(b_req.req_code);
FOR tl_req IN cur_req_name(b_req.rqmt_id) LOOP
add_piece(tl_req.rqmt_name);
END concat_columns;
END requirements_util;
EXEC ctx_ddl.drop_section_group('rqmt_sectioner');
EXEC ctx_ddl.drop_preference('rqmt_user_ds');
BEGIN
ctx_ddl.create_preference('rqmt_user_ds', 'USER_DATASTORE');
ctx_ddl.set_attribute('rqmt_user_ds', 'procedure', sys_context('userenv','current_schema')||'.'||'requirements_util.concat_columns');
ctx_ddl.set_attribute('rqmt_user_ds', 'output_type', 'VARCHAR2');
END;
CREATE INDEX rqmt_cidx ON pjt_requirements_b(req_code)
INDEXTYPE IS CTXSYS.CONTEXT
PARAMETERS ('DATASTORE rqmt_user_ds
SYNC (ON COMMIT)'); -
Regular expression in oracle for hypen
Hi,
I want to match a word "{color:#993300}83-ASG{color}" using regexp_like and i used '{color:#993300}^83-*{color}' pattern to match this word but this also matches words like "{color:#993300}8307-YUF{color}". could anyone please tell me what pattern should i use to match words like {color:#993300}83-ASG{color}.
Also i need to know the similar pattern in oracle for the "{color:#993300}\b{}{color}" used in .net.
Thanks in advance.
PrasadHi Prasad,
Your regex could be as simple as '^83-'
So, not much use for a regular expression:
SQL> with test_data as (select '83-ASG' txt from dual union all
select '8307-YUF' from dual)
-- end of test data
select txt from test_data
where txt like '83-%'
TXT
83-ASG
1 row selected.Unless, you add some more value to it, perhaps like
SQL> with test_data as (select '83-ASG' txt from dual union all
select '8307-YUF' from dual)
-- end of test data
select txt from test_data
where regexp_like(txt, '^83-[[:upper:]]{3}$')
TXT
83-ASG
1 row selected.Regards
Peter -
Regular Expression/Replace - Oracle 7.3
Hi!
I am trying the regular expression SQL functions of 10g to Oracle 7.3 and it seems the older version does not cover this feature yet.
"Aaaa,Bbbb" --> "Aaaa, Bbbb"
REPLACE *",[0-9A-Za-z]"* WITH *", "*
The string pattern is to look for comma-punctuations that is not followed immediately by whitespacess so I can replace this with a comma followed by a whitespace.
Any workaround for this?Hi,
Welcome to the forum!
kitsune wrote:
Hi!
I am trying the regular expression SQL functions of 10g to Oracle 7.3 and it seems the older version does not cover this feature yet.You're right; regular expressions only work in Oracle 10.1 and higher.
>
>
"Aaaa,Bbbb" --> "Aaaa, Bbbb"
REPLACE *",[0-9A-Za-z]"* WITH *", "*
The string pattern is to look for comma-punctuations that is not followed immediately by whitespacess so I can replace this with a comma followed by a whitespace.
Any workaround for this?You're best bet in Oracle 7.3 would be a user-defined function. That's a very old version; don't expect much.
Do you know anything else about the string? For example, is there some character (say ~) that never occurs in the string? Will there ever be two (or more) whitespace characters after punctuation? What characters do you consider to be whitespace? Which are punctuation? Depending on the answers, you might be able to do something with nested REPLACE and/or TRANSLATE functions. -
Need regular expression for oracle date format 'DD-MON-YYYY'
Hi,
Can anybody tell me the regular expression to validate date in 'DD-MON-YYYY'.
My concept is i have a table with just two columns item_name and item_date
Both fields are varchar2 and i want to fetch those records from this table which have valid date format('DD-MON-YYYY').If it must be a regexp, this is a starter for you, note it carries the caveats mentioned by both posters above and in the linked thread
mkr02@ORA11GMK> with data as (select '10-jan-2012' dt from dual
2 union all select '10-111-2012' from dual
3 union all select 'mm-jan-2012' from dual
4 union all select '10-jan-12' from dual)
5 select
6 dt,
7 case when regexp_like(dt,'[[:digit:]]{2}-[[:alpha:]]{3}-[[:digit:]]{4}','i') then 1 else 0 end chk
8 from data
9 /
DT CHK
10-jan-2012 1
10-111-2012 0
mm-jan-2012 0
10-jan-12 0It will not validate content, only string format.
And to emphasis the points made in the linked thread - dates in text columns is poor design. Always. -
Without using a regular expressions in oracle 9i
dear all;
I have the following test data below
insert into p
(id)
values
('\G1\G2');
insert into p
(id)
values
('\A1\');
insert into p
(id)
values
('\B1\B2\B3');
insert into p
(id)
values
('\J1\J2\J3\J4');and this is the output I desire though
ID
G1
null
B2
J3the output is gotten by looking at the second to the last entry and extracting it....
so for \G1\G2 the second to the last entry was G1 hence we have G1
for \A1\ there is no second to the last entry and that is why it is null
for \B1\B2\B3 the second to the last entry was B2Hi,
user13328581 wrote:
... the output is gotten by looking at the second to the last entry and extracting it....
so for \G1\G2 the second to the last entry was G1 hence we have G1
for \A1\ there is no second to the last entry and that is why it is nullSo backslashes at the end of id don't matter. Whether id is
'\AI',
'\A1\' or
'\A1\\\\\\\\\\\\'
there's only entry in id, and so you want to return NULL. Is that right?
Here's one way to do that in Oracle 9:
WITH got_pos AS
SELECT id
, INSTR ( RTRIM (id, '\')
, -1
, 2) + 1 AS pos_from
, INSTR ( RTRIM (id, '\')
, -1
, 1) AS pos_to
FROM p
SELECT id
, CASE
WHEN pos_from > 1
THEN SUBSTR ( id
, pos_from
, pos_to - pos_from
END AS penult
FROM got_pos
ORDER BY id
; -
Simple regular expression in oracle query
hi guys, I have this challenge.
say I have a query:
select name, user_name, object_type from questions;
now, for the column object type, I can get values that end in 'Q' followed by number.
So object type columns can be 00Q1, ABCQ2, 56Q7 e.t.c. It can be any number really.
The thing is, I want to add a small grouping, so that for the rows which have the object type column ending in Q followed by number, I can have an additional column whose value changes to question.
So the query now becomes:
select name, user_name, object_type, column_type from questions;
So column_type can be question if object type ends with Q and a number, otherwise just give it a default value, like Others or something.
Is this possible and if so how can I please achieve it.
Thanks very much.Hope this will help.
SQL> with t as
2 ( select '00Q1' element_name from dual union all
3 select 'ABCQ2' from dual union all
4 select '56QA7 ' from dual union all
5 select '56Q7 ' from dual union all
6 select 'ABCQA' from dual)
7 select * from t
8 where regexp_like(element_name,'\Q[0-9]')
9 /
ELEMEN
00Q1
ABCQ2
56Q7Or something like this
SQL> with t as
2 ( select '00Q1' element_name from dual union all
3 select 'ABCQ2' from dual union all
4 select '56QA7 ' from dual union all
5 select '56Q7 ' from dual union all
6 select 'ABCQA' from dual)
7 select t.*, DECODE(regexp_instr(element_name,'\Q[0-9]'),0,'Not Found',element_name ) comments
8 from t
9 /
ELEMEN COMMENTS
00Q1 00Q1
ABCQ2 ABCQ2
56QA7 Not Found
56Q7 56Q7
ABCQA Not FoundEdited by: Saubhik on May 18, 2010 6:41 AM -
Introduction to regular expressions ...
I'm well aware that there are already some articles on that topic, some people asked me to share some of my knowledge on this topic. Please take a look at this first part and let me know if you find this useful. If yes, I'm going to continue on writing more parts using more and more complicated expressions - if you have questions or problems that you think could be solved through regular expression, please post them.
Introduction
Oracle has always provided some character/string functions in its PL/SQL command set, such as SUBSTR, REPLACE or TRANSLATE. With 10g, Oracle finally gave us, the users, the developers and of course the DBAs regular expressions. However, regular expressions, due to their sometimes cryptic rules, seem to be overlooked quite often, despite the existence of some very interesing use cases. Beeing one of the advocates of regular expression, I thought I'll give the interested audience an introduction to these new functions in several installments.
Having fun with regular expressions - Part 1
Oracle offers the use of regular expression through several functions: REGEXP_INSTR, REGEXP_SUBSTR, REGEXP_REPLACE and REGEXP_LIKE. The second part of each function already gives away its purpose: INSTR for finding a position inside a string, SUBSTR for extracting a part of a string, REPLACE for replacing parts of a string. REGEXP_LIKE is a special case since it could be compared to the LIKE operator and is therefore usually used in comparisons like IF statements or WHERE clauses.
Regular expressions excel, in my opinion, in search and extraction of strings, using that for finding or replacing certain strings or check for certain formatting criterias. They're not very good at formatting strings itself, except for some special cases I'm going to demonstrate.
If you're not familiar with regular expression, you should take a look at the definition in Oracle's user guide Using Regular Expressions With Oracle Database, and please note that there have been some changes and advancements in 10g2. I'll provide examples, that should work on both versions.
Some of you probably already encountered this problem: checking a number inside a string, because, for whatever reason, a column was defined as VARCHAR2 and not as NUMBER as one would have expected.
Let's check for all rows where column col1 does NOT include an unsigned integer. I'll use this SELECT for demonstrating different values and search patterns:
WITH t AS (SELECT '456' col1
FROM dual
UNION
SELECT '123x'
FROM dual
UNION
SELECT 'x123'
FROM dual
UNION
SELECT 'y'
FROM dual
UNION
SELECT '+789'
FROM dual
UNION
SELECT '-789'
FROM dual
UNION
SELECT '159-'
FROM dual
UNION
SELECT '-1-'
FROM dual
SELECT t.col1
FROM t
WHERE NOT REGEXP_LIKE(t.col1, '^[0-9]+$')
;Let's take a look at the 2nd argument of this REGEXP function: '^[0-9]+$'. Translated it would mean: start at the beginning of the string, check if there's one or more characters in the range between '0' and '9' (also called a matching character list) until the end of this string. "^", "[", "]", "+", "$" are all Metacharacters.
To understand regular expressions, you have to "think" in regular expressions. Each regular expression tries to "fit" an available string into its pattern and returns a result beeing successful or not, depending on the function. The "art" of using regular expressions is to construct the right search pattern for a certain task. Using functions like TRANSLATE or REPLACE did already teach you using search patterns, regular expressions are just an extension to this paradigma. Another side note: most of the search patterns are placeholders for single characters, not strings.
I'll take this example a bit further. What would happen if we would remove the "$" in our example? "$" means: (until the) end of a string. Without this, this expression would only search digits from the beginning until it encounters either another character or the end of the string. So this time, '123x' would be removed from the SELECTION since it does fit into the pattern.
Another change: we will keep the "$" but remove the "^". This character has several meanings, but in this case it declares: (start from the) beginning of a string. Without it, the function will search for a part of a string that has only digits until the end of the searched string. 'x123' would now be removed from our selection.
Now there's a question: what happens if I remove both, "^" and "$"? Well, just think about it. We now ask to find any string that contains at least one or more digits, so both '123x' and 'x123' will not show up in the result.
So what if I want to look for signed integer, since "+" is also used for a search expression. Escaping is the name of the game. We'll just use '^\+[0-9]+$' Did you notice the "\" before the first "+"? This is now a search pattern for the plus sign.
Should signed integers include negative numbers as well? Of course they should, and I'll once again use a matching character list. In this list, I don't need to do escaping, although it is possible. The result string would now look like this: '^[+-]?[0-9]+$'. Did you notice the "?"? This is another metacharacter that changes the placeholder for plus and minus to an optional placeholder, which means: if there's a "+" or "-", that's ok, if there's none, that's also ok. Only if there's a different character, then again the search pattern will fail.
Addendum: From this on, I found a mistake in my examples. If you would have tested my old examples with test data that would have included multiple signs strings, like "--", "-+", "++", they would have been filtered by the SELECT statement. I mistakenly used the "*" instead of the "?" operator. The reason why this is a bad idea, can also be found in the user guide: the "*" meta character is defined as 0 to multiple occurrences.
Looking at the values, one could ask the question: what about the integers with a trailing sign? Quite simple, right? Let's just add another '[+-] and the search pattern would look like this: '^[+-]?[0-9]+[+-]?$'.
Wait a minute, what happened to the row with the column value "-1-"?
You probably already guessed it: the new pattern qualifies this one also as a valid string. I could now split this pattern into several conditions combined through a logical OR, but there's something even better: a logical OR inside the regular expression. It's symbol is "|", the pipe sign.
Changing the search pattern again to something like this '^[+-]?[0-9]+$|^[0-9]+[+-]?$' [1] would return now the "-1-" value. Do I have to duplicate the same elements like "^" and "$", what about more complicated, repeating elements in future examples? That's where subexpressions/grouping comes into play. If I want only certain parts of the search pattern using an OR operator, we can put those inside round brackets. '^([+-]?[0-9]+|[0-9]+[+-]?)$' serves the same purpose and allows for further checks without duplicating the whole pattern.
Now looking for integers is nice, but what about decimal numbers? Those may be a bit more complicated, but all I have to do is again to think in (meta) characters. I'll just use an example where the decimal point is represented by ".", which again needs escaping, since it's also the place holder in regular expressions for "any character".
Valid decimals in my example would be ".0", "0.0", "0.", "0" (integer of course) but not ".". If you want, you can test it with the TO_NUMBER function. Finding such an unsigned decimal number could then be formulated like this: from the beginning of a string we will either allow a decimal point plus any number of digits OR at least one digits plus an optional decimal point followed by optional any number of digits. Think about it for a minute, how would you formulate such a search pattern?
Compare your solution to this one:
'^(\.[0-9]+|[0-9]+(\.[0-9]*)?)$'
Addendum: Here I have to use both "?" and "*" to make sure, that I can have 0 to many digits after the decimal point, but only 0 to 1 occurrence of this substrings. Otherwise, strings like "1.9.9.9" would be possible, if I would write it like this:
'^(\.[0-9]+|[0-9]+(\.[0-9]*)*)$'Some of you now might say: Hey, what about signed decimal numbers? You could of course combine all the ideas so far and you will end up with a very long and almost unreadable search pattern, or you start combining several regular expression functions. Think about it: Why put all the search patterns into one function? Why not split those into several steps like "check for a valid decimal" and "check for sign".
I'll just use another SELECT to show what I want to do:
WITH t AS (SELECT '0' col1
FROM dual
UNION
SELECT '0.'
FROM dual
UNION
SELECT '.0'
FROM dual
UNION
SELECT '0.0'
FROM dual
UNION
SELECT '-1.0'
FROM dual
UNION
SELECT '.1-'
FROM dual
UNION
SELECT '.'
FROM dual
UNION
SELECT '-1.1-'
FROM dual
SELECT t.*
FROM t
;From this select, the only rows I need to find are those with the column values "." and "-1.1-". I'll start this with a check for valid signs. Since I want to combine this with the check for valid decimals, I'll first try to extract a substring with valid signs through the REGEXP_SUBSTR function:
NVL(REGEXP_SUBSTR(t.col1, '^([+-]?[^+-]+|[^+-]+[+-]?)$'), ' ')Remember the OR operator and the matching character collections? But several "^"? Some of the meta characters inside a search pattern can have different meanings, depending on their positions and combination with other meta characters. In this case, the pattern translates into: from the beginning of the string search for "+" or "-" followed by at least another character that is not "+" or "-". The second pattern after the "|" OR operator does the same for a sign at the end of the string.
This only checks for a sign but not if there also only digits and a decimal point inside the string. If the search string fails, for example when we have more than one sign like in the "-1.1-", the function returns NULL. NULL and LIKE don't go together very well, so we'll just add NVL with a default value that tells the LIKE to ignore this string, in this case a space.
All we have to do now is to combine the check for the sign and the check for a valid decimal number, but don't forget an option for the signs at the beginning or end of the string, otherwise your second check will fail on the signed decimals. Are you ready?
Does your solution look a bit like this?
WHERE NOT REGEXP_LIKE(NVL(REGEXP_SUBSTR(t.col1,
'^([+-]?[^+-]+|[^+-]+[+-]?)$'),
'^[+-]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)[+-]?$'
)Now the optional sign checks in the REGEXP_LIKE argument can be added to both ends, since the SUBSTR won't allow any string with signs on both ends. Thinking in regular expression again.
Continued in Introduction to regular expressions ... continued.
C.
Fixed some embarrassing typos ... and mistakes.
cdExcellent write up CD. Very nice indeed. Hopefully you'll be completing parts 2 and 3 some time soon. And with any luck, your article will encourage others to do the same....I know there's a few I'd like to see and a few I'd like to have a go at writing too :-)
-
Changeparticular characters in a string by using regular expressions ...
Hello Everyone,
I am trying to write a function by using oracles regular expression function REGEXP_REPLACE but I could not succed till now.
My problem as follows, I have a text in a column for example let say 'sdfsdf Sdfdfs Sdfd' I want replace all s and S characters with X and make the text look like 'XdfXdf XdfdfX Xdfd'.
Is it possible by using regular expressions in oracle ?
Can you give me some clues ?
Thank youSSU wrote:
Hello Everyone,
I am trying to write a function by using oracles regular expression function REGEXP_REPLACE but I could not succed till now.
My problem as follows, I have a text in a column for example let say 'sdfsdf Sdfdfs Sdfd' I want replace all s and S characters with X and make the text look like 'XdfXdf XdfdfX Xdfd'.
Is it possible by using regular expressions in oracle ?
Can you give me some clues ?
Thank you
SQL> SELECT
2 regexp_replace('sdfsdf Sdfdfs Sdfd','s|S','X') from dual;
REGEXP_REPLACE('SD
XdfXdf XdfdfX XdfdRegards,
Achyut -
Hi Experts,
After going through some documentation on regular expressions in Oracle I have tried to draw some conclusions about the same. As I wasn’t much confident on how the patterns are built, I have tried to interpret them by looking at the output. It’s basically a reverse engineering I have tried to do.
Please let me know if my interpretations are correct. Any additions /suggestions/corrections are most welcome.
Some of the examples may lack conclusions, please ignore those.
select regexp_substr('1PSN/231_3253/ABc','^([[:alnum:]]*)') from dual;
Output: 1PSN
Interpreted as:
^ From the start of the source string
([[:alnum:]]*) zero or more occurrences of alphanumeric characters
select regexp_substr('@@/231_3253/ABc','@*([[:alnum:]]+)') from dual;
Output: 231
Interpreted as:
@* Search for zero or more occurrences of @
([[:alnum:]]+) followed by one or more occurrences of alphanumeric characters
Note: In the above example oracle looks for @(zero times or more) immediately followed by alphanumeric characters.
Since a '/' comes between @ and 231 the o/p is 0 occurences of @ + one or more occurrences of alphanumerics.
select regexp_substr('1@/231_3253/ABc','@+([[:alnum:]]*)') from dual;
Output: @
Interpreted as:
@+ one or more ocurrences of @
([[:alnum:]]*) followed by 0 or more occurrences of alphanumerics
select regexp_substr('1@/231_3253/ABc','@+([[:alnum:]]+)') from dual;
Output: Null
Interpreted as:
@+ one or more occurences of @
([[:alnum:]]+) followed by one or more occurences of aplhanumerics
select regexp_substr('@1PSN/231_3253/ABc125','([[:digit:]]+)$') from dual;
Output: 125
Interpreted as:
([[:digit:]]+) one or more occurences of digits only
$ at the end of the string
select regexp_substr('@1PSN/231_3253/ABc','([^[:digit:]]+)$') from dual;
output: /ABc
Interpreted as:
([^[:digit:]]+)$ one or more occurrences of non-digit literals at the end of the string
'^' inside square brackets marks the negation of the class
Look for http:// followed by a substring of one or more alphanumeric characters and optionally, a period (.)
SELECT REGEXP_SUBSTR('Go to http://www.oracle.com/products and click on database','http://([[:alnum:]]+\.?){3,4}/?') RESULT
FROM dual;
Output: http://www.oracle.com
Interpreted as:
[[:alnum:]]+ one or more occurences of alplanumeric characters
\.? dot optionally (backslash represents escape sequence,? represents optionally)
{3,4} 3 or 4 times
/? followed by forward slash optionally
If you have www.oracle.co.uk; {3,4} extracts it for you as well
Validate email:
select case when
REGEXP_LIKE('[email protected]',
'^([[:alnum:]]+(\_?|\.))([[:alnum:]]*)@([[:alnum:]]+)(.([[:alnum:]]+)){1,2}$') then 'Match Found'
else 'No Match Found'
end
as output from dual;
Interpreted as:
([[:alnum:]]+(\_?|\.)) one or more occurrences of alpha numerics optionally followed by an underscore or dot
([[:alnum:]]*) followed by 0 or more occurrences of alplhanumerics
@ followed by @
([[:alnum:]]+) followed by one or more occurrences of alplhanumerics
(.([[:alnum:]]+)){1,2} followed by a dot followed by alphanumerics from once till max of twice (Ex- .com or .co.uk)
Output: Match Found
Input: [email protected]
Output: Match Found
Input: [email protected]
Output: No Match Found
Truncate the part, ending with digits
select regexp_substr('Yahoo11245@US','^.*[[:digit:]]',1) from dual;
Output: Yahoo11245
select regexp_substr('*Yahoo*11245@US','^.*[[:digit:]]',1) from dual;
Output: *Yahoo*11245
Interpreted as:
.* zero or more occurrences of any characters (dot signifies any character)
Replace 2 to 8 spaces with single space
select regexp_replace('Hello you OPs there','[[:space:]]{2,8}',' ')
from dual;
Search for control characters
select case when
regexp_like('Super' || chr(13) || 'Star' ,'[[:cntrl:]]')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Output: Match Found
Search for lower case letters only with a string length varying from a min of 3 to max of 12
select case when
regexp_like('terminator' ,'^[[:lower:]]{3,12}$')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
4th character must be a special character
select case when
regexp_like('ter*minator' ,'^...[^[:alnum:]]')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Ouput: Match Found
Case Sensitive Search
select case when
regexp_like('Republic Of Africa' ,'of','c')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Output: No match found
c stands for case sensitive
select case when
regexp_like('Republic Of africa' ,'of','i')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Output: Match Found
i stands for case insensitive
Two consecutive occurences of characters from a to z
select regexp_substr('Republicc Of Africaa' ,'([a-z])\1', 1,1,'i') from dual;
Output: cc
Interpreted as:
([a-z]) character set a-z
\1 consecutive occurence of any character
1 starting from 1st character in the string
1 First occurence
i case insensitive
Three consecutive occurences of characters from 6 to 9
select case when
regexp_like('Patch 10888 applied' ,'([7-9])\1\1')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Output: Match Found
Phone validator:
select case when
regexp_like('123-44-5555' ,'^[0-9]{3}-[0-9]{2}-[0-9]{4}$')
then 'Match Found'
else 'No Match Found'
end
as output from dual;
Output: Match Found
Input: 111-222-3333
Output: No match found
Interpreted as:
^ start of the string
[0-9]{3} three ocurrences of digits from 0-9
- followed by hyphen
[0-9]{2} two ocurrences of digits from 0-9
- followed by hyphen
[0-9]{4} four ocurrences of digits from 0-9
$ end of the string
************************************************************************Source Links:
http://www.psoug.org/reference/regexp.html
http://www.oracle.com/technology/obe/obe10gdb/develop/regexp/regexp.htm
Edited by: Preta on Feb 25, 2010 4:38 PM
Corrected the example for www.oracle.com
Edited by: Preta Incorported Logan's commentsHi,
It looks like you have a good understanding of how regular expressions work.
You can put comments like the ones in your message directly in the code. For example, your validate e-mail code could be re-written
select case
when REGEXP_LIKE ( '[email protected]'
, '^' || -- Starting from the beginning of the string
'(' || -- Begin \1
'[[:alnum:]]+'|| -- 0 or more alphnumerics
'(\_?|\.)' || -- optional underscore or dot
')' || -- End \1
'([[:alnum:]]*)'|| -- 0 or more alphnumerics
'@' || -- @ sign
'([[:alnum:]]+)'|| -- 1 or more alpanumerics
'(' || -- Begin \5
'\.' || -- dot
'([[:alnum:]]+)'
|| -- 1 or more alphanumerics
')' || -- End \5
'{1,2}' || -- \5 can occur 1 or 2 times
'$' -- End of string
then 'Match Found'
else 'No Match Found'
end as output
from dual;I find this easier to debug and maintain.
There's no denying, it does make the code very long. You be the judge of when to do this.
You use parentheses and \ unnceccessarily sometimes. That's not really an error; if you find they make the code easier to develop and maintain, use them as much as you like.
For example, about the 4th line of the regular expression as I formatted it above:
'(\_?|\.)' || -- optional underscore or dotUnderscore has no special meaning in regular expressions (only in LIKE), so you don't have to escape it.
I might write that line:
'(_|\.)?' || -- optional underscore or dotjust because I think it's clearer.
I think you forgot a \ about 7 lines later:
'\.' || -- dotBe very careful about testing patterns that include literal dots; always make sure that a random character, like ~ , fails in a place where a dot is expected. -
Regular expression...
Hello,
I'm trying to understand regular expressions in Oracle 10g. I have to say that I'm a little lost. Can anyone tell me how can I extract using REGEXP_SUBSTR function the text between the parentheses?
Here is a sample code:
WITH T1 AS (
SELECT 1 A, 'My first name (Hello) is not so long...' B FROM DUAL
UNION ALL
SELECT 2, 'My second (World) name is shorter.' FROM DUAL
UNION ALL
SELECT 3, q'[(I'm) My third name is stupid.]' FROM DUAL
UNION ALL
SELECT 4, '[My forth name end with (a regexp)]' FROM DUAL
SELECT B, REGEXP_SUBSTR(B, '\([[:alpha:]]+\)' FROM T1;As result, I want
Hello
World
I'm
a regexpThe result should not include the parentheses.
I tried the previous code, but I have an exception:
Paramètre IN ou OUT absent dans l'index :: 1Thanks for your helpWITH T1 AS
( SELECT 1 A, 'My first name (Hello) is not so long...' B FROM DUAL
UNION ALL
SELECT 2, 'My second (World) name is shorter.' FROM DUAL
UNION ALL
SELECT 3, q'[(I'm) My third name is stupid.]' FROM DUAL
UNION ALL
SELECT 4, '[My forth name end with (a regexp)]' FROM DUAL
SELECT B, REGEXP_replace(B, '.*\((.*)\).*','\1') FROM T1;Ravi Kumar -
The regular expression.
Hello all, I have need to learn the regular expression for teh Oracle database. Can
anyones tell to me where I find the informations - good sites that give the secrets ;)
I have already look but would like some advices. NóraNóra wrote:
Hello all, I have need to learn the regular expression for teh Oracle database. Can
anyones tell to me where I find the informations - good sites that give the secrets ;)
I have already look but would like some advices. NóraHi Nóra,
I have been looking at this recently myself and I have a few
sites bookmarked. Enjoy the intricacies of regexen - with any
luck, you won't even have to learn any PL/SQL ;)
Good introdution
http://www.zytrax.com/tech/web/regex.htm
Simple summary of Oracle's regular expressions
http://www.regular-expressions.info/oracle.html
Not forgetting the Wiki (contains table with vi
equivalents - for those of us who use a real editor ;)
http://en.wikipedia.org/wiki/Regular_expression
This site should be one of your main ports of call for any Oracle issues.
Good forums also - better software than Oracle themselves.
http://www.orafaq.com/node/2404
Morgan's Library - used to be psoug.org - don't know what happened - anyone?
Daniel posts here from time to time
http://www.morganslibrary.org/reference/regexp.html
And,not forgetting the Oracle docco.
http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_regexp.htm
http://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_re.htm
Also look on OTN for a .pdf for introduction.HTH,
Paul... -
Off Topic: Books about Regular Expression
Hi
Somebody can to indicate books about Regular Expression in Oracle ?
ThanksRegex tag of Blog of Volder.
http://volder-notes.blogspot.com/search/label/Regular%20Expressions
This entry mentions my regex solution :-)
http://volder-notes.blogspot.com/2007/10/removing-duplicate-elements-from-string.html
By the way
My regex homepage mentions regex problems of perl like regex (regex of EmEditor).
http://www.geocities.jp/oraclesqlpuzzle/regex/
example questions (written by Japanese language)
http://www.geocities.jp/oraclesqlpuzzle/regex/regex-2-1.html
http://www.geocities.jp/oraclesqlpuzzle/regex/regex-3-5.html
http://www.geocities.jp/oraclesqlpuzzle/regex/regex-4-4.html
Maybe you are looking for
-
How can I get adobe player on ipad 2
How can I download adobe flash player on ipad 2 ?
-
Importing photos into iPhoto from Hard Drive
Mike just downloaded our back up onto our newish Mac after our Macbook bravely went to it's grave in coffee. I'm now trying to import about 100 - 200G of photos into iPhoto from my hard drive. I really do not want to spend the whole time selectin
-
Cisco Network Assistant, unable to add a switch
I have a network running some 20 switches, two controllers and many AP's. All the devices that should be able to connect to cisco network assistant can successfully. However there is one switch that will show in neighbours but will give the message
-
Connecting to Oracle 8i.7 Database on Application Server 10g (10.1.2)
Hi Dear All i have gust installed Oracle Application Infrastructure & middle tire 10g(10.1.2) and i am asking for the capability to connect (After Configuring Tnsname) to Oracle Database 8i(8.1.7.0.0) the message after trying to connect is : Connecti
-
We have tvo computer Can I make more than one website Hove do i do?
Can I bulit a website one one cumputer Than built another website on another cumputer? I have tryed !It don´t work [email protected]