我试图从Accept标题中提取版本的值,可以是形式
"vnd.example-com.foo+json; version=1.1"
Run Code Online (Sandbox Code Playgroud)
这是我提取版本的代码
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"
}
Run Code Online (Sandbox Code Playgroud)
当我调用上述用于提取版本的函数时(例如可以是v1.0或v1.5或v2.5的形式)
getResourceVersion("vnd.example-com.foo+json; version=1.1")
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
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)
Run Code Online (Sandbox Code Playgroud)
我认为我在我的正则表达式中做错了或者输入字符串有一些非法的字符,我无法用我对正则表达式的有限知识来识别.帮我找出原因.
如果有可能写一个没有那个是明确的并做同样的事情,它会建议反对(ab)使用look-behind.
只需使用模式:
version=(.*)
Run Code Online (Sandbox Code Playgroud)
你想要的是捕获第1组.
| 归档时间: |
|
| 查看次数: |
10073 次 |
| 最近记录: |