Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio Kotlin regex different than expected

I'm having a problem with a specific regex that is returning a different value than expected when running in Android Studio.

Scenario:

The code is simple:

val regex = "(?<=N|E|\\G)\\d{2}(?=\\d*$)".toRegex()
print("${regex.findAll("N2032354345").count()}")

This should print 5 as there are 5 matches in this string (https://regex101.com/r/6PDbkI/1) and if we run in on Ideone.com or in Kotlin Playground, the result is the expected 5.

However, in Android Studio, the result is 1:

Theory:

It seems that the regex in Android Studio is failing to use the \G operator (which might be related to Kotlin split with regex work not as expected)

Anyone faced the same problem? Is there any way to change the regex to a similar one that isn't failing in Android Studio? Am I missing some setting?

like image 568
Pedro Oliveira Avatar asked Nov 09 '18 14:11

Pedro Oliveira


1 Answers

Android Pattern documentation lists \G as a supported operator:

\G    The end of the previous match

Hence, it sounds like an Android Studio bug.

Until it is fixed, you may use a work around for your scenario that involves just a dozen digits in the input:

val regex = "(?<=[NE]\\d{0,100})\\d{2}(?=\\d*$)".toRegex()

The pattern matches:

  • (?<=[NE]\d{0,100}) - a position that is immediately preceded with N or E and 0 to 100 digits
  • \d{2} - two digits
  • (?=\d*$) - that are followed with 0 or more digits to the end of the string.
like image 91
Wiktor Stribiżew Avatar answered Nov 08 '22 21:11

Wiktor Stribiżew