在Scala中的给定索引之后在字符串中查找正则表达式匹配 [英] Find regular expression match in string after a given index in Scala
本文介绍了在Scala中的给定索引之后在字符串中查找正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为字符串上的正则表达式找到匹配项(如果有),但只在给定索引之后进行测试.例如:
I want to find a match (if any) for a regular expression on a string, but only testing after a given index. For example:
val p = "[a-zA-Z_][a-zA-Z0-9_]*".r
val t = "const pi = 3.141592"
val m = p.findFirstMatchIn(t, start=5) // not real syntax
也就是说,我想忽略字符串的前 n = 5
个字符.有没有办法做到这一点?
That is, I want to ignore the first n = 5
characters of the string. Is there any way to do that?
推荐答案
Scala 的 .r
语法是原始 java.util.regex.{Pattern, Matcher}代码> API.原始 API 提供更多控制.使用 <代码>Matcher.region
:
Scala's .r
syntax is a thin wrapper around the original java.util.regex.{Pattern, Matcher}
API. The original API provides more control. Use Matcher.region
:
scala> val m = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*").matcher(t)
scala> m.region(5, t.size)
scala> m.find()
scala> m.group(0)
res6: String = pi
这篇关于在Scala中的给定索引之后在字符串中查找正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文