val p = """^(\d+)(?:-(\d+))?$""".r
val m = p.findAllIn("2")
for i <- 1 to m.groupCount do println(m.group(i))
Output:
2
null
This is unexpected, perhaps a bug? There should only be one group, not two. regex101 behaves as expected, and only returns one group matching 2
.
#groupCount
returns all groups present in the matcher’s backing pattern, not just the matched groups, and this feels quite reasonable. Calling #group(Int)
on a non-matching group yields null
- which is unfortunate, but probably an artifact of directly mapping to the underlying Java regex API.
Yes, so…?
The links go to Scala documentation. And reporting two groups makes sense, no matter the language. Cf.
$ python -c 'import re; print(re.search(re.compile("^(\\d+)(?:-(\\d+))?$"), "2").groups())'
('2', None)
The only complaint I have with the Scala behavior is getting a null
rather than a proper Option
for an unmatched group - and this is likely due to Java heritage.
1 Like