java.lang.IndexOutOfBoundsException: No group 1 | Pattern matching

java, regex, scala

Solution

It'd advise against (ab)using look-behind, if it is possible to write one without that is clear and does the same thing.

Just use the pattern:

version=(.*)

And what you want will be in capturing group 1.

Problem

I am trying to extract the value of version from `Accept` header which can be of the form ``` "vnd.example-com.foo+json; version=1.1" ``` here is my code for extracting the version ``` val resourceVersionPattern: Pattern = Pattern.compile("(?<=version=).*") def getResourceVersion(acceptHeader: String): String = { import java.util.regex.Matcher val matcher: Matcher = resourceVersionPattern.matcher(acceptHeader) if(matcher.find()) ("v" + matcher.group(1)).trim() else "v1.0" } ``` When I am invoking the above function which is intended to extract version (for example can be of the form v1.0 or v1.5 or v2.5) ``` getResourceVersion("vnd.example-com.foo+json; version=1.1") ``` I get following exception: ``` java.lang.IndexOutOfBoundsException: No group 1 at java.util.regex.Matcher.group(Matcher.java:487) at .getResourceVersion(<console>:12) at .<init>(<console>:11) at .<clinit>(<console>) at .<init>(<console>:11) at .<clinit>(<console>) at $print(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704) at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920) at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43) at scala.tools.nsc.io.package$$anon$2.run(package.scala:25) at java.lang.Thread.run(Thread.java:744) ``` I think I am doing something wrong in my regex or the input string has some illegal charecters which I am not able to identify with my limited knowledge of Regular expression. Help me find out the reason.

Original source