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
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 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 -
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. -
Simple regular expression problem
Hello,
I need help with regular expressions. I have a situation when I need to get data from one table to another and I think my problem can be solved using REG EXP, but I don't know how to use them properly.
I need to seperate varchar2 fileld whcih is basically number/number into 2 seperate number fields
CREATE TABLE tst (CODE VARCHAR2(10));
INSERT INTO tst VALUES('10/15');
INSERT INTO tst VALUES('13/12');
INSERT INTO tst VALUES('30');
INSERT INTO tst VALUES('15');
CREATE TABLE tst2 (po NUMBER, co NUMBER); I need to get code into co and po columns. I think result should look something like this, but:
INSERT INTO tst2
SELECT regexp_substr(CODE 'something here to get the number before /') AS po,
regexpr_substr(CODE 'something here to get number after') AS co
FROM tst; Any help appreciatedHi Blu,
Yes, I have tested with "0" in the figure (like 10/20 30/40). And it worked that time and then I replied. :) :)
But Still it has a problem in pattern and rectified it below.
Like :-
SQL> select regexp_substr('10/40','[^/][0 9]',1,2) DD from dual;
DD
40
But if I (The way you test) use a non zero value like 43 ; below query will not return 43.
SQL> select regexp_substr('15/43','[^/][0 9]',1,2) DD from dual;
DD
My pattern has a slight mistake("-" missing between 0 and 9) and I changed and retested . Correct pattern - '[^/][0-9]' and now it will return 43..
SQL> select regexp_substr('15/43','[^/][0-9]',1,2) dd from dual ;
DD
43this '[^/]+' pattern also works fine.
Thank you for pointing out Blu; as I came to know lot more about patterns.
Regards,
Ashutosh -
Help: Verify or Suggest a Simple Regular Expression
I'm trying to do a mapping from a title to a file name portion of a URL. Thus the result needs to follow the rules as specified here:
http://labs.apache.org/webarch/uri/rfc/rfc3986.html#unreserved
I identified the following characters as legal: a-z / 0-9 / "-" / "." / "_" / "~"
Everything else has to be converted to an underscore.
I came up with the following expression:
someString.replaceAll("[^a-zA-Z0-9-._~]", "_")Is that correct? I spent a lot of time trying to figure out regular expressions, but it seems like everyone (i.e. PHP, TextPad and now Java) has a slightly different version and to top it off, there not very good tutorials or explanations. I dread regular expressions!!!
Can anyone help please?HoganWang wrote:
Ur regular expression is right. The regular expression has simple and complex versions. If the replaceAll is frequently called, it is recommended to use Pattern to compile the regular expressions first.How does the expression know that the hypen isn't part of range? I guess the only way is that it is between alphabetical letters or numbers.
In terms of efficiency. This is called once per page request i.e.
somedomain.com/somecategory/title_title_title
Well, I need to be able to translate title&title$title to title_title_title. It doesn't seem like a pre-compiling the regular expression will speed it up since between page requests, it won't remember fields or am I wrong? -
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. -
Use of Regular Expressions in BI Query Designer
Hello All,
For a particular requirement in Inventory, I have the following to be achieved:
If at the input selection screen, if Plant entered is 'AB12', then it should show batches only startign with 'J' and if Plant entered is 'AB13' then the query output should show only batches with '$****K' (where * indicates any digit and $ indicates any character.
Will I be able to achieve this at query level, since my design for Inventory is already existing.
One way is I can always take it to a new cube and write some routines in transformation to achieve the same, but that would in essence duplicate data at multiple places.
Request to guide me for the same.
Thank you.
Regards,
Kunal GandhiHi,
If you are able, create a Structure in your Query and add 2 Selections to it.
Restrict 1 Selection on Plant AB12, and Batch J****** using Contains Pattern as described by Mansi. Restrict the other Selection on Plant AB13, and Batch $*****K again using Contains Pattern.
Activate Zero Suppression on this Structure.
When the user selects a Plant in the input, only the Selection which contains that Plant will be displayed.
Hope this helps. Sorry it is so long after the question, I found this while looking for something else.
Steve -
[CS 5.5/JS/OSX] Simple regular expression crashes InDesign
I'm in the process of migrating a script from CS3 to CS5.5. When trying the script with no modifications it causes InDesign to stall, and I have to force close it. After running through the script line by line I found the culprit:
/A(_|-)?B\.jpg/.test("A-C.jpg")
This causes the entire script engine to freeze.
With CS3 it works fine. Also when do I slight change it works fine:
/A(-|_)?B\.jpg/.test("A-C.jpg")
Any idea what's going on? Is it a bug in the scripting engine?Any ideas exactly what kind of expressions triggers the bug?
I rewrote my expression to not contain phrases like /(a|b|abc)?/. Instead I use /[ab]?(abc)?/, which is close enough, and seems to not trigger the bug. -
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 Question
Or ist it not so simple? Decide yourself:
If a random text (lets say "Nader") does not contain for example the string "Bush", then it shall match the pattern. But how would that pattern look like?
First I tried ^(Bush). But it doesn't work. Then I tried lots of other things and googling, with no success.
Any ideas for that simple thing?Let me get this straight.
Text area A will have some text in it. Let's say the user supplies "Bush".
Right?
Text area B is allowed to contain any text in it except an exact match of what is in text area A.
Right?
if (B.getText().equals(A.getText())) { // or however you get the string from a TextArea
// Uh-oh! They match!
}But it can't be that simple, else you woldn't have posted.
So what are you looking for?
Can A contain stuff that is to be interpreted as a regex? That is If A has "B.*sh" then B must not start with "B" and end with "sh"?
Will either or both of them be line-based? That is:
A:
Bush
Cheny
B:
Clinton
Bush
and no line from A must match any line from B?
Maybe I'm just dense, but I still don't really understand what you're looking for, or why you need regex since you seem to be just looking for an exact string match. Initially you said "contain", which suggests " .* Bush .* " but later you seem to be talking about exact matches. -
A simple regular expression....
What I need to do is find occurances of |A in a string, and replace it with another string. This sounds like a perfect use of the String.replaceAll() method! So, I gave it a try, and failed. The code String.replaceAll("|A", "ReplacedText"); doesnt actually replace |A. I was wondering if I need an escape character before the pipe or something since pipe I believe is used in regex logic. Thanks for any help in advance.
You're right, you need to do:newString = oldString.replaceAll("\\|A", replacementText);...using the double backslash to ensure that a single backslash gets into the actual regex.
Maybe you are looking for
-
Digital Input Cannot Display this Video Mode Optimum Resolution 1280 x 1024 60hz.
HP Pavilion h8-1360t, Windows7 home premium 64-bit, AMD Radeon HD 7570 graphics card. error message: Digital Input Cannot Display this Video Mode Optimum Resolution 1280 x 1024 60hz. I get the error message as soon as Windows opens and the desktop
-
No bootable device... can't open Mac OS X or anything in fact! Help!
got a new iMac and just used bootcamp to make a partition. It was made successfully. but then i quit and didn't continue to install Windows. After a shower, i guess my iMac went to sleep, but i couldn't wake it up using my apple keyboard or trackpa
-
Cant connect to wifi with my apple tv which makes it completely useless. Can anyone please let me know if there is anyway to fix this issue. Im going insane. thank you
-
how do you hide an app on iPhone 4?
-
Problem installing adobe x11 trial Error 1935
after downloading with adobe download assistant it gets about 90% through the installation then encounters a problem and undose everything and the green status bar goes back to the left. what can i do i really need to use this trial by morning. pleas