Evgenia Evgenia - 5 months ago 17
Java Question

How to use Oracle regular expression in Java or how to map them?

How can I use Oracle regular expressions in Java to get the same result or how can I build Java regular expression based on Oracle regular expression.

Oracle:

declare
str1 varchar2(50);
begin
str1 := REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA', ',[^,]+,');
DBMS_OUTPUT.PUT_LINE(str1);
end;


Result:

, Redwood Shores,


Java:

String str1 = null;
Pattern pattern = Pattern.compile(",[^,]+,");
Matcher matcher = pattern.matcher("500 Oracle Parkway, Redwood Shores, CA");
if (matcher.find())
{
str1 = matcher.group(1);
}


But this regular expression doesn't work in Java. It fails with this exception:

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1
at java.util.regex.Matcher.group(Matcher.java:538)
at mousemover.Playground.main(Playground.java:16)


Maybe there is some algorithm to map regex?

Answer Source

Use Matcher.group() or Matcher.group(0) to find the match. Calling for group 1 will not work as you do not specify a so-called capturing group in your regex.

From the Javadoc of Matcher.group(int):

Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().