Evgenia Evgenia - 1 year ago 51
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.


str1 varchar2(50);
str1 := REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA', ',[^,]+,');


, Redwood Shores,


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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download