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?
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 ...
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.
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 \ .
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 tom.group()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With