Android Studio Kotlin regex different than expecte

2019-05-03 05:05发布

问题:

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?

回答1:

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.