Oracle String Functions
Oracle String Functions
The ASCII function returns the decimal representation in the database character set of the first character
of char. Example: ASCII('b') =98
The CHR function returns the character having the binary equivalent to n as a VARCHAR2 value in either
CHR
the database character set. Example: CHR(10)||CHR(13) = carriage return plus line feed.
The COALESCE function returns the first non-null expr in the expression list. At least one expr must not
COALESCE be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null. Example:
select COALESCE(col1, col2, col3) FROM emp;
The CONCAT function returns the concatenation of 2 strings. You can also use the || command for this.
CONCAT
Example: CONCAT('abc','def') = 'abcdef'
The CONVERT function converts a string from one characterset to another. The datatype of the returned
value is VARCHAR2. Example: CONVERT('This is an example','UTF-8','WE8ISO8859P1') SELECT
CONVERT
CONVERT(' A B C D E ', 'US7ASCII', 'WE8ISO8859P1') FROM DUAL; = A E I ? ? A
BCDE?
The DUMP function returns a VARCHAR2 value containing the datatype code, length in bytes, and
DUMP
internal representation of expr. The returned result is always in the database character set.
INSTR
Returns the position of a String within a String. For more information see Oracle instr function
INITCAP
Transform String to init cap Example: INITCAP('ORADEV') = 'Oradev'
INSTRB
Returns the position of a String within a String, expressed in bytes.
INSTRC
Returns the position of a String within a String, expressed in Unicode complete characters
INSTR2
Returns the position of a String within a String, expressed in UCS2 code points
INSTR4
Returns the position of a String within a String, expressed in UCS4 code points
The LENGTH functions returns the length of char. LENGTH calculates length using characters as defined
LENGTH
by the input character set. Example: length('oradev.com') = 10
LENGTHB
Returns the length of a string, expressed in bytes.
The LOWER function returns a string with all lower case characters. Example: LOWER('ORADEV') =
LOWER
'oradev'
Add characters to the left of a string until a fixed number is reached. Example: lpad('abc',8,'x') =
LPAD
'xxxxxabc'. If the last parameter is not specified, spaces are added to the left.
LTRIM removed characters from the left of a string if they are equal to the specified string. Example:
LTRIM
ltrim('aaaaaabc','a') = 'bc' If the last parameter is not specified, spaces are removed from the left side.
The replace function replaces every occurrence of a search_string with a new string. If no new string is
REPLACE
specified, all occurrences of the search_string are removed. Example: replace('a1a1a1','a','2') = '212121'.
REVERSE
Reverses the characters of a String. Example: REVERSE('oradev.com') = 'moc.vedaro'
Add characters to the right of a string until a fixed number is reached. Example: rpad('abc',8,'x') =
RPAD
'abcxxxxx'. If the last parameter is not specified, spaces are added to the right.
RTRIM removed characters from the right of a string if they are equal to the specified string. Example:
RTRIM
rtrim('bcaaaaaa','a') = 'bc' If the last parameter is not specified, spaces are removed from the right side.
SOUNDEX returns a character string containing the phonetic representation of char. This function lets you
SOUNDEX compare words that are spelled differently, but sound alike in English. Example: select * from emp where
lastname SOUNDEX('SMITH');
SUBSTR
Returns a substring. For more information see Oracle substring
SUBSTRB
Returns a substring expressed in bytes instead of characters.
SUBSTRC
Returns a substring expressed in Unicode code points instead of characters.
SUBSTR2
Returns a substring using USC2 code points.
SUBSTR4
Returns a substring using USC4 code points.
TRANSLATE returns expr with all occurrences of each character in from_string replaced by its
corresponding character in to_string. Characters in expr that are not in from_string are not replaced.
TRANSLATE
Example: SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '___') FROM DUAL; =
'SQL_Plus_Users_Guide'
The TRIM function trims specified characters from the left and/or right. If no characters are specified, the
TRIM
left and right spaces are left out. Example: trim(' Oradev dot com ') = 'Oradev dot com'.
|| (pipes)
With pipes you can concattenate strings. Example 'Oradev'||'.com' = 'Oradev.com'.
UPPER
Transform a string to all upper case characters. Example: UPPER('oradev') = 'ORADEV'
ASCII
VSIZE
Returns a comma in the specified position. You can specify multiple commas in a number format
model.
Restrictions:
A comma cannot appear to the right of a decimal character or period in a number format
model.
$9999
0999
9990
Returns value with the specified number of digits with a leading space if positive or with a leading
minus if negative.
9
9999
Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the
fixed-point number.
B9999
Returns blanks for the integer part of a fixed-point number when the integer part is zero (regardless
of "0"s in the format model).
C999
Returns in the specified position the ISO currency symbol (the current value of
the NLS_ISO_CURRENCY parameter).
99D99
Returns in the specified position the decimal character, which is the current value of
the NLS_NUMERIC_CHARACTER parameter. The default is a period (.).
Restriction: You can specify only one decimal character in a number format model.
EEEE
FM
FM90.9
9G999
L999
Returns in the specified position the local currency symbol (the current value of
the NLS_CURRENCY parameter).
MI
9999MI
9999PR
RN
RN
rn
rn
TM
TM
The default is TM9, which returns the number in fixed notation unless the output exceeds 64
characters. If output exceeds 64 characters, then Oracle automatically returns the number in
scientific notation.
Restrictions:
You can follow this element only with 9 or E (only one) or e (only one).
U9999
Returns in the specified position the "Euro" (or other) dual currency symbol (the current value of
the NLS_DUAL_CURRENCY parameter).
999V99
Returns a value multiplied by 10n (and if necessary, round it up), where n is the number of 9's after
the "V".
Restrictions:
This element accepts only positive values or 0. Negative values return an error.
You can precede this element only with 0 (which returns leading zeroes) or FM. Any other
elements return an error. If you specify neither 0 nor FM with X, then the return always has
1 leading blank.
from
XML Functions
Oracle provides XML functions to operate on or return XML documents or fragments.
Here is a list of all the XML functions (in version 10.2):
Function
Usage
Description
APPENDCHILDXML
APPENDCHILDXML(XMLTYPE_instance,XPath_string,value_expr) or
APPENDCHILDXML(XMLTYPE_instance,XPath_string,value_expr,namespace_string)
APPENDCHILDXML appends a user-supplied value onto the target XML as the child of the node indicated by an XPath
expression. XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes onto which one or more child nodes are to be
appended. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial
slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The value_expr specifies one or more nodes of XMLType. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
DELETEXML
DELETEXML(XMLTYPE_instance, XPath_string) or
DEPTH(correlation_integer)
DEPTH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the number
of levels in the path specified by the UNDER_PATH condition with the same correlation variable. The correlation_integer
can be any NUMBER integer. Use it to correlate this ancillary function with its primary condition if the statement contains
multiple primary conditions. Values less than 1 are treated as 1.
EXTRACT (XML)
EXTRACT(XMLTYPE_instance,XPath_string) or
EXTRACT(XMLTYPE_instance,XPath_string, namespace_string)
EXTRACT (XML) is similar to the EXISTSNODE function. It applies a VARCHAR2 XPath string and returns an XMLType
instance containing an XML fragment. You can specify an absolute XPath_string with an initial slash or a relative
XPath_string by omitting the initial slash. If you omit the initial slash, the context of the relative path defaults to the root
node. The optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or
namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath expression(s).
EXISTSNODE
EXISTSNODE(XMLTYPE_instance,XPath_string) or
EXISTSNODE(XMLTYPE_instance,XPath_string, namespace_string)
EXISTSNODE determines whether traversal of an XML document using a specified path results in any nodes. It takes as
arguments the XMLType instance containing an XML document and a VARCHAR2 XPath string designating a path. The
optional namespace_string must resolve to a VARCHAR2 value that specifies a default mapping or namespace mapping
for prefixes, which Oracle Database uses when evaluating the XPath expression(s).
The namespace_string argument defaults to the namespace of the root element. If you refer to any subelement in
Xpath_string, then you must specify namespace_string, and you must specify the "who" prefix in both of these
arguments.
EXTRACTVALUE
EXTRACTVALUE(XMLTYPE_instance,XPath_string) or
EXTRACTVALUE(XMLTYPE_instance,XPath_string, namespace_string)
The EXTRACTVALUE function takes as arguments an XMLType instance and an XPath expression and returns a scalar
value of the resultant node. The result must be a single node and be either a text node, attribute, or element. If the result
is an element, then the element must have a single text node as its child, and it is this value that the function returns. You
can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you
omit the initial slash, the context of the relative path defaults to the root node.
INSERTCHILDXML
INSERTCHILDXML inserts a user-supplied value into the target XML at the node indicated by the XPath expression.
Compare this function with INSERTXMLBEFORE.
XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes into which the one or more child nodes are to be
inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial
slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The child_expr specifies the one or more element or attribute nodes to be inserted.
The value_expr is an fragment of XMLType that specifies one or more notes being inserted. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
INSERTXMLBEFORE
INSERTXMLBEFORE(XMLTYPE_instance,XPath_string, value_expr) or
INSERTXMLBEFORE(XMLTYPE_instance,XPath_string, value_expr, namespace_string)
INSERTXMLBEFORE inserts a user-supplied value into the target XML before the node indicated by the XPath
expression. Compare this function with INSERTCHILDXML.
XMLType_instance is an instance of XMLType.
The XPath_string is an Xpath expression indicating one or more nodes into which one or more child nodes are to be
inserted. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial
slash. If you omit the initial slash, the context of the relative path defaults to the root node.
The value_expr is a fragment of XMLType that defines one or more nodes being inserted and their position within the
parent node. It must resolve to a string.
The optional namespace_string provides namespace information for the XPath_string. This parameter must be of type
VARCHAR2.
PATH
PATH(correlation_integer)
PATH is an ancillary function used only with the UNDER_PATH and EQUALS_PATH conditions. It returns the relative
path that leads to the resource specified in the parent condition.
The correlation_integer can be any NUMBER integer and is used to correlate this ancillary function with its primary
condition. Values less than 1 are treated as 1.
SYS_DBURIGEN
SYS_DBURIGEN(column,text)
SYS_DBURIGen takes as its argument one or more columns or attributes, and optionally a rowid, and generates a URL
of datatype DBURIType to a particular column or row object. You can then use the URL to retrieve an XML document
from the database.
SYS_XMLAGG
SYS_XMLAGG(expr) or
SYS_XMLAGG(expr,fmt)
SYS_XMLAgg aggregates all of the XML documents or fragments represented by expr and produces a single XML
document. It adds a new enclosing element with a default name ROWSET. If you want to format the XML document
differently, then specify fmt, which is an instance of the XMLFormat object.
SYS_XMLGEN
SYS_XMLGEN(expr) or
SYS_XMLGEN(expr,fmt)
SYS_XMLGen takes an expression that evaluates to a particular row and column of the database, and returns an
instance of type XMLType containing an XML document. The expr can be a scalar value, a user-defined type, or an
XMLType instance.
If expr is a scalar value, then the function returns an XML element containing the scalar value.
If expr is a type, then the function maps the user-defined type attributes to XML elements.
If expr is an XMLType instance, then the function encloses the document in an XML element whose default tag name is
ROW.
By default the elements of the XML document match the elements of expr. For example, if expr resolves to a column
name, then the enclosing XML element will be the same column name. If you want to format the XML document
differently, then specify fmt, which is an instance of the XMLFormat object.
UPDATEXML
UPDATEXML(XMLTYPE_instance,XPath_string, value_expr) or
UPDATEXML(XMLTYPE_instance,XPath_string, value_expr, namespace_string)
UPDATEXML takes as arguments an XMLType instance and an XPath-value pair and returns an XMLType instance with
the updated value. If XPath_string is an XML element, then the corresponding value_expr must be an XMLType instance.
If XPath_string is an attribute or text node, then the value_expr can be any scalar datatype. You can specify an absolute
XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, the
context of the relative path defaults to the root node. The datatypes of the target of each XPath_string and its
corresponding value_expr must match. The optional namespace_string must resolve to a VARCHAR2 value that
specifies a default mapping or namespace mapping for prefixes, which Oracle Database uses when evaluating the XPath
expression(s).
XMLAGG
XMLAGG(XMLTYPE_instance) or
XMLAGG(XMLTYPE_instance, order_by_clause)
XMLAgg is an aggregate function. It takes a collection of XML fragments and returns an aggregated XML document. Any
arguments that return null are dropped from the result.
XMLAgg is similar to SYS_XMLAgg except that XMLAgg returns a collection of nodes but it does not accept formatting
using the XMLFormat object. Also, XMLAgg does not enclose the output in an element tag as does SYS_XMLAgg.
Within the order_by_clause, Oracle Database does not interpret number literals as column positions, as it does in other
uses of this clause, but simply as number literals.
XMLCDATA
XMLCDATA(value_expr)
XMLCData generates a CDATA section by evaluating value_expr. The value_expr must resolve to a string. The value
returned by the function takes the following form:
If the resulting value is not a valid XML CDATA section, then the function returns an error.The following conditions apply
to XMLCData:
The value_expr cannot contain the substring ]]>.
If value_expr evaluates to null, then the function returns null.
XMLCOLATTVAL
XMLCOLATTVAL(value_expr AS c_alias) or
XMLCOLATTVAL(value_expr AS c_alias, value_expr AS c_alias,..)
XMLColAttVal creates an XML fragment and then expands the resulting XML so that each XML fragment has the name
column with the attribute name. You can use the AS c_alias clause to change the value of the name attribute to
something other than the column name. You must specify a value for value_expr. If value_expr is null, then no element is
returned. Restriction on XMLColAttVal: You cannot specify an object type column for value_expr.
XMLCOMMENT
XMLCOMMENT(value_expr)
XMLComment generates an XML comment using an evaluated result of value_expr. The value_expr must resolve to a
string. It cannot contain two consecutive dashes (hyphens). The value returned by the function takes the following form:
<!--string-->
If value_expr resolves to null, then the function returns null.
XMLCONCAT
XMLCONCAT(XMLTYPE_instance) or
XMLCONCAT(XMLTYPE_instance, XMLTYPE_instance, ...)
XMLConcat takes as input a series of XMLType instances, concatenates the series of elements for each row, and returns
the concatenated series. XMLConcat is the inverse of XMLSequence.
Null expressions are dropped from the result. If all the value expressions are null, then the function returns null.
XMLFOREST
XMLFOREST(value_expr AS c_alias) or
XMLFOREST(value_expr AS c_alias, value_expr AS c_alias,..)
XMLForest converts each of its argument parameters to XML, and then returns an XML fragment that is the
concatenation of these converted arguments.
If value_expr is a scalar expression, then you can omit the AS clause, and Oracle Database uses the column name as
the element name.
If value_expr is an object type or collection, then the AS clause is mandatory, and Oracle uses the specified c_alias as
the enclosing tag. The c_alias can be up to 4000 characters.
If value_expr is null, then no element is created for that value_expr.
XMLPARSE
XMLPARSE(DOCUMENT, value_expr) or
XMLPARSE(DOCUMENT, value_expr WELLFORMED) or
XMLPARSE(CONTENT, value_expr) or
XMLPARSE(CONTENT, value_expr WELLFORMED)
XMLParse parses and generates an XML instance from the evaluated result of value_expr. The value_expr must resolve
to a string. If value_expr resolves to null, then the function returns null.
If you specify DOCUMENT, then value_expr must resolve to a singly rooted XML document.
If you specify CONTENT, then value_expr must resolve to a valid XML value.
When you specify WELLFORMED, you are guaranteeing that value_expr resolves to a well-formed XML document, so
the database does not perform validity checks to ensure that the input is well formed.
XMLPI
XMLPI(identifier) or
XMLPI(NAME identifier) or
XMLPI(NAME identifier , value_expr)
XMLPI generates an XML processing instruction using identifier and optionally the evaluated result of value_expr. A
processing instruction is commonly used to provide to an application information that is associated with all or part of an
XML document. The application uses the processing instruction to determine how best to process the XML document.
XMLQUERY
XMLQUERY lets you query XML data in SQL statements. It takes an XQuery expression as a string literal, an optional
context item, and other bind variables and returns the result of evaluating the XQuery expression using these input
values.
XQuery_string is a complete XQuery expression, including prolog.
The expr in the XML_passing_clause is an expression returning an XMLType that is used as the context for evaluating
the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. The result of
evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an
AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string.
RETURNING CONTENT indicates that the result from the XQuery evaluation is either an XML 1.0 document or a
document fragment conforming to the XML 1.0 semantics.
XMLROOT
XMLROOT(...)
XMLROOT lets you create a new XML value by providing version and standalone properties in the XML root information
(prolog) of an existing XML value. If the value_expr already has a prolog, then the database returns an error. If the input
is null, then the function returns null.
XMLSEQUENCE
XMLSEQUENCE(XMLTYPE_instance) or
XMLSEQUENCE(sys_refcursor_instance) or
XMLSEQUENCE(sys_refcursor_instance, fmt)
returns as an XMLSequence type an XML document for each row of the cursor.
Because XMLSequence returns a collection of XMLType, you can use this function in a TABLE clause to unnest the
collection values into multiple rows, which can in turn be further processed in the SQL query.
XMLSERIALIZE
XMLSERIALIZE(DOCUMENT, value_expr) or
XMLSERIALIZE(DOCUMENT, value_expr AS datatype) or
XMLSERIALIZE(CONTENT, value_expr) or
XMLSERIALIZE(CONTENT, value_expr AS datatype)
XMLTABLE
XMLTable maps the result of an XQuery evaluation into relational rows and columns. You can query the result returned
by the function as a virtual relational table using SQL.
XMLTRANSFORM
XMLTRANSFORM(XMLTYPE_instance,XMLTYPE_instance)
XMLTransform takes as arguments an XMLType instance and an XSL style sheet, which is itself a form of XMLType
instance. It applies the style sheet to the instance and returns an XMLType.
This function is useful for organizing data according to a style sheet as you are retrieving it from the database.
Description
CC
Century
SCC
YYYY
SYYY
IYYY
YY
RR
YEAR
Year in characters
SYEAR
BC
BC/AD Indicator *
MM
MONTH
MON
JAN, FEB
WW
Weeknumber (i.e. 1)
IW
DDD
DD
DAY
FMDAY
DY
Julian Day (number of days since January 1 4713 BC, where January 1 4713 BC is 1 in Oracle)
HH
HH12
HH24
AM
AM or PM
PM
AM or PM
MI
SS
SSSSS
DS
DL
Abbreviated era name. Valid only for calendars: Japanese Imperial, ROC Official and Thai Buddha.. (Inputonly)
EE
FF
FF1..FF9
The fractional seconds. Use with timestamp. The digit controls the number of decimal digits used for
fractional seconds.
FM
FX
Format Exact: requires exact pattern matching between data and format model.
IYY or IY or
the last 3,2,1 digits of the ISO standard year. Output only
I
RM
RR
RRRR
The last 2 digits of the year when used for output. Accepts fout-digit years when used for input.
SCC
CC
Century
SP
Spelled format. Can appear of the end of a number element. The result is always in english. For example
month 10 in format MMSP returns "ten"
SPTH
TH
TS
TZD
TZH
TZM
TZR
Function
Usage
Description
ABS
ABS(n)
ACOS
ACOS(n)
ASIN
ASIN(n)
ATAN
ATAN(n)
ATAN2(n1,n2) or ATAN2(n1/n2)
BITAND(expr1,expr2)
CEIL(n)
COS(n)
COSH
COSH(n)
EXP
EXP(n)
ATAN2
BITAND
CEIL
COS
FLOOR
LN
LOG
MOD
NANVL
POWER
FLOOR(n)
LN(n)
LOG(n2,n1)
LOG returns the logarithm, base n2, of n1. The base n1 can
be any positive value other than 0 or 1 and n2 can be any
positive value. This function takes as arguments any numeric
datatype or any nonnumeric datatype that can be implicitly
converted to a numeric datatype. If any argument is
BINARY_FLOAT or BINARY_DOUBLE, then the function
returns BINARY_DOUBLE. Otherwise the function returns
NUMBER.
MOD(n2,n1)
NANVL(n2,n1)
POWER(n2,n1)
REMAINDER
REMAINDER(n2,n1)
SIGN
SIGN(n)
SIN(n)
SINH
SINH(n)
SQRT
SQRT(n)
SIN
TAN(n)
TANH(n)
TAN
TANH
WIDTH_BUCKET
WIDTH_BUCKET(expr,min_value,
max_value,num_buckets)
Sysdate
ADD_MONTHS
+,- (plus/minus)
In Oracle you can add or substract a number of days from a date. Example: sysdate+5
means systemdate/time plus 5 days
GREATEST
With the greatest function you can select the date/time that is the highest in a range of
date/times. Example: greatest (sysdate+4,sysdate,sysdate-5) = sysdate+4.
LEAST
With the least function you can select the earliest date/time in a range of date/times.
Example: least(sysdate+4,sysdate,sysdate-5) = sysdate-5.
LAST_DAY
Returns the last_day of a month based on the month the passed date is in. Example:
last_day(sysdate) returns the last day of this month.
MONTHS_BETWEEN
Returns the number of months between two dates. The number is not rounded.
Example: months_between(sysdate, to_date('01-01-2007','dd-mm-yyyy')) returns the
number of months since jan 1, 2007.
NEXT_DAY
Date of next specified date following a date NEXT_DAY(, ) Options are SUN, MON, TUE,
WED, THU, FRI, and SAT SELECT NEXT_DAY(SYSDATE, 'FRI') FROM dual; NOTE:
This can be dependend on NLS_SETTINGS!
ROUND
Returns date rounded to the unit specified by the format model. If you omit the format,
the date is rounded to the nearest day ROUND(, ) SELECT ROUND(TO_DATE('27-OCT00'),'YEAR') NEW_YEAR FROM dual;
TRUNC
Convert a date to the date without time (0:00h) Example: TRUNC(sysdate) returns today
without time.
TO_CHAR(date,format_mask) Converts a date to a string using a format mask. Format masks are explained here
<complexType>
<sequence>
<element name = "id"
type = "samp:departmentIdType"/>
<element name = "name" type = "string"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>',
TRUE, TRUE, FALSE, FALSE);
end;
Now you can create an XMLSchema-based table, as shown in the following example:
CREATE TABLE XmlTest OF XMLType
XMLSCHEMA "http://www.oradev.com/sample.xsd"
ELEMENT "company";
Now XML can be inserted into the XmlTest table as following:
INSERT INTO XmlTest VALUES(
xmltype.createxml('<?xml version="1.0"?>
<samp:company xmlns:samp="http://www.oradev.com/sample.xsd" >
<department>
<id>10</id>
<name>Accounting</name>
</department>
</samp:company>'));
CREATE TABLE XmlTest2 (
id number
, xml_data XmlType)
XMLTYPE xml_data STORE AS OBJECT RELATIONAL
XMLSCHEMA "http://www.oradev.com/sample.xsd"
ELEMENT "company";
INSERT INTO XmlTest2 VALUES(1,
xmltype.createxml('<?xml version="1.0"?>
<samp:company xmlns:samp="http://www.oradev.com/sample.xsd" >
<department>
<id>10</id>
<name>Accounting</name>
</department>
</samp:company>'));
It's also possible to create constraints on on the XMLSchema-based table.
General Information
Anchoring Characters
Equivalence Classes
Match Options
Posix Characters
Character
Class
Description
Character
Class
Description
==
Oracle supports the equivalence classes through the POSIX '[==]' syntax. A base
letter and all of its accented versions constitute an equivalence class. For
example, the equivalence class '[=a=]' matches and . The equivalence
classes are valid only inside the bracketed expression
Character
Class
Description
Character
Class
Description
[:alnum:]
Alphanumeric characters
[:alpha:]
Alphabetic characters
[:blank:]
[:cntrl:]
[:digit:]
Numeric digits
[:graph:]
[:lower:]
[:print:]
Printable characters
[:punct:]
Punctuation characters
[:space:]
Quantifier Characters
[:upper:]
[:xdigit:]
Hexidecimal characters
Character
Class
Match 0 or 1 time
{m}
{m,}
{m, n}
\n
Alternative Matching
And Grouping
Characters
Character
Class
|
()
[char]
Demo Table
Description
Description
Separates alternates, often used with grouping operator ()
Groups subexpression into a unit for alternations, for quantifiers, or for
backreferencing (see "Backreferences" section)
Indicates a character list; most metacharacters inside a character list are
understood as literals, with the exception of character classes, and the ^ and metacharacters
CREATETABLEtest(
testcolVARCHAR2(50));
INSERTINTOtestVALUES('abcde');
INSERTINTOtestVALUES('12345');
INSERTINTOtestVALUES('1a4A5');
INSERTINTOtestVALUES('12a45');
INSERTINTOtestVALUES('12aBC');
INSERTINTOtestVALUES('12abc');
INSERTINTOtestVALUES('12ab5');
INSERTINTOtestVALUES('12aa5');
INSERTINTOtestVALUES('12AB5');
INSERTINTOtestVALUES('ABCDE');
INSERTINTOtestVALUES('1235');
INSERTINTOtestVALUES('12.45');
INSERTINTOtestVALUES('1a4b5');
INSERTINTOtestVALUES('135');
INSERTINTOtestVALUES('145');
INSERTINTOtestVALUES('15');
INSERTINTOtestVALUES('abcd');
INSERTINTOtestVALUES('abcde');
INSERTINTOtestVALUES('ae');
INSERTINTOtestVALUES('Steven');
INSERTINTOtestVALUES('Stephen');
INSERTINTOtestVALUES('111.222.3333');
INSERTINTOtestVALUES('222.333.4444');
INSERTINTOtestVALUES('333.444.5555');
INSERTINTOtestVALUES('abcdefabcdefabcxyz');
COMMIT;
REGEXP_COUNT
REGEXP_COUNT(<source_string>,<pattern>[[,<start_position>],
[<match_parameter>]])
Syntax
Count's occurrences
based on a regular
expression
matchparameter:
'c'=casesensitive
'i'=caseinsensitivesearch
'm'=treatsthesourcestringasmultiplelines
'n'=allowstheperiod(.)wildcharactertomatchnewline
'x'=ignorewhitespacecharacters
SELECTREGEXP_COUNT(testcol,'2a',1,'i')RESULT
FROMtest;
SELECTREGEXP_COUNT(testcol,'e',1,'i')RESULT
FROMtest;
REGEXP_INSTR
Syntax
REGEXP_INSTR(<source_string>,<pattern>[[,<start_position>][,
<occurrence>][,<return_option>][,<match_parameter>][,
<sub_expression>]])
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
[[:alpha:]]{3}',1,1,0,'i')RESULT
FROMDUAL;
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
[[:alpha:]]{3}',1,2,0,'i')RESULT
FROMDUAL;
SELECTREGEXP_INSTR('500OraclePkwy,RedwoodShores,CA','[o]
[[:alpha:]]{3}',1,2,1,'i')RESULT
FROMDUAL;
Find the position of try,
trying, tried or tries
SELECTREGEXP_INSTR('Wearetryingtomakethesubjecteasier.',
'tr(y(ing)?|(ied)|(ies))')RESULTNUM
FROMDUAL;
SELECTtestcol,REGEXP_INSTR(testcol,'ab',1,1,0,'i',0)
FROMtest;
Using Sub-Expression
option
SELECTtestcol,REGEXP_INSTR(testcol,'ab',1,1,0,'i',1)
FROMtest;
SELECTtestcol,REGEXP_INSTR(testcol,'a(b)',1,1,0,'i',1)
FROMtest;
REGEXP_LIKE
Syntax
REGEXP_LIKE(<source_string>,<pattern>,<match_parameter>)
AlphaNumeric
Characters
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alnum:]]{5}');
Alphabetic Characters
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:alpha:]]{5}');
Control Characters
INSERTINTOtestVALUES('zyx'||CHR(13)||'wvu');
COMMIT;
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:cntrl:]]{1}');
Digits
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:digit:]]{5}');
Lower Case
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:lower:]]{5}');
Printable Characters
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{5}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{6}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:print:]]{7}');
Punctuation
TRUNCATETABLEtest;
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:punct:]]');
Spaces
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{3}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:space:]]{5}');
Upper Case
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]{2}');
SELECT*
FROMtest
WHEREREGEXP_LIKE(testcol,'[[:upper:]]{3}');
SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^ab*');
SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^..a.');
SELECTtestcol
Contains two
consecutive occurances FROMtest
of the letter 'a' or 'z'
WHEREREGEXP_LIKE(testcol,'([az])\1','i');
Begins with 'Ste' ends
with 'en' and contains
either 'v' or 'ph' in the
center
SELECTtestcol
FROMtest
WHEREREGEXP_LIKE(testcol,'^Ste(v|ph)en$');
Use a regular
expression in a check
constraint
CREATETABLEmytest(c1VARCHAR2(20),
CHECK(REGEXP_LIKE(c1,'^[[:alpha:]]+$')));
Identify SSN
CREATETABLEssn_test(
ssn_colVARCHAR2(20));
INSERTINTOssn_testVALUES('111223333');
INSERTINTOssn_testVALUES('111=223333');
INSERTINTOssn_testVALUES('111A23333');
INSERTINTOssn_testVALUES('1112233339');
INSERTINTOssn_testVALUES('111223333');
INSERTINTOssn_testVALUES('987654321');
COMMIT;
SELECTssn_col
fromssn_test
WHEREREGEXP_LIKE(ssn_col,'^[09]{3}[09]{2}[09]{4}$');
REGEXP_REPLACE
Syntax
REGEXP_REPLACE(<source_string>,<pattern>,
<replace_string>,<position>,<occurrence>,<match_parameter>)
coltestcolformata15
colresultformata15
SELECTtestcol,REGEXP_REPLACE(testcol,
'([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',
'(\1)\2\3')RESULT
FROMtest
WHERELENGTH(testcol)=12;
SELECTtestcol,REGEXP_REPLACE(testcol,'(.)','\1')RESULT
WHEREtestcollike'S%';
Replace multiple
spaces with a single
space
SELECTREGEXP_REPLACE('500OracleParkway,Redwood
Shores,CA','(){2,}','')RESULT
FROMDUAL;
SELECTREGEXP_REPLACE('GeorgeMcGovern','([[:lower:]])
([[:upper:]])','\1\2')CITY
FROMDUAL;
(Produces 'George Mc Govern')
FROMDUAL;
Demo
CREATETABLEt(
testcolVARCHAR2(10));
INSERTINTOtVALUES('1');
INSERTINTOtVALUES('2');
INSERTINTOtVALUES('3new');
colnewvalformata10
SELECTLENGTH(testcol)len,testcolorigval,
REGEXP_REPLACE(testcol,'\W+$','')newval,
LENGTH(REGEXP_REPLACE(testcol,'\W+$',''))newlen
FROMt;
SELECTREGEXP_REPLACE('[email protected]','^(\S+)@(\S+)','\2')
FROMDUALd
WHERE
REGEXP_LIKE('[email protected]','^[AZaz09._%+]+@([AZa
z09]+.)?+[AZaz]{2,63}$')
REGEXP_SUBSTR
Syntax
REGEXP_SUBSTR(source_string,pattern
[,position[,occurrence
[,match_parameter]]])
characters and
optionally, a period (.)
clickondatabase',
'http://([[:alnum:]]+\.?){3,4}/?')RESULT
FROMDUAL;
SELECTREGEXP_SUBSTR('Wearetryingtomakethesubject
FROMDUAL;
SELECTREGEXP_SUBSTR('system/pwd@orabase:1521:sidval',
FROMDUAL;
CREATETABLEregexp(
INSERTINTOregexp
(testcol)
VALUES
('One|Two|Three|Four|Five');
SELECT*FROMregexp;
SELECTREGEXP_SUBSTR(testcol,'[^|]+',1,3)
FROMregexp;
Equivalence classes
Parsing Demo
SELECTREGEXP_SUBSTR('iSelfSchoolingNOTISelfSchooling',
'[[=i=]]SelfSchooling')RESULT
FROMDUAL;
setserveroutputon
DECLARE
xVARCHAR2(2);
yVARCHAR2(2);
cVARCHAR2(40):='1:3,4:6,8:10,3:4,7:6,11:12';
BEGIN
x:=REGEXP_SUBSTR(c,'[^:]+',1,1);
y:=REGEXP_SUBSTR(c,'[^,]+',3,1);
dbms_output.put_line(x||''||y);
END;
/
Gary Whitaker wrote in with an addition to this parsing demo, and had the
following comments:
The parsing demo above uses the regular expression '[^,]+' which does not work when
there is a NULL element in the list. This could result in returning the wrong element's