Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

oracle

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?

like image 350
Evgenia Avatar asked May 12 '17 07:05

Evgenia


People also ask

What is the use of regular expression in Oracle?

Regular expressions enable you to search for patterns in string data by using standardized syntax conventions. You specify a regular expression by means of the following types of characters: Metacharacters, which are operators that specify search algorithms. Literals, which are the characters for which you are ...

What is regular expression How does it help implement it with Java program?

A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations. Java does not have a built-in Regular Expression class, but we can import the java. util.

What does \\ mean in Java regex?

String regex = "\\."; Notice that the regular expression String contains two backslashes after each other, and then a . . The reason is, that first the Java compiler interprets the two \\ characters as an escaped Java String character. After the Java compiler is done, only one \ is left, as \\ means the character \ .


1 Answers

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

like image 178
Malte Hartwig Avatar answered Sep 29 '22 07:09

Malte Hartwig