8

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?

10
  • Sounds more like a bug to me, considering it works fine in the playground Commented Nov 9, 2018 at 14:27
  • That's what I thought @Zoe. Do you happen to know what is the best place to report such issue? Commented Nov 9, 2018 at 14:28
  • And that's correct @WiktorStribiżew. But I'm developing for Android Studio, which is not returning 5, but 1 instead (which is NOK) Commented Nov 9, 2018 at 14:30
  • I think you may use a workaround like "(?<=[NE]\\d{0,100})\\d{2}(?=\\d*$)" (you may adjust the 100 value). Commented Nov 9, 2018 at 14:31
  • I can confirm that that workarround works @WiktorStribiżew. But it seems to be an ugly one :/ Commented Nov 9, 2018 at 14:32

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thx @WiktorStribiżew +1 for saving my day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.