Android Studio Kotlin正则表达式与预期不同 [英] Android Studio Kotlin regex different than expected

查看:75
本文介绍了Android Studio Kotlin正则表达式与预期不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个特定的正则表达式问题,该正则表达式在Android Studio中运行时返回的值与预期值不同.

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

场景:

代码很简单:

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

这应该打印5,因为此字符串中有5个匹配项( https://regex101.com/r /6PDbkI/1 ),如果我们在 Ideone.com

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.

但是,在Android Studio中,结果为1:

However, in Android Studio, the result is 1:

理论:

Android Studio中的正则表达式似乎无法使用\G运算符(这可能与用正则表达式拆分的Kotlin有关工作没有按预期进行)

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)

有人遇到同样的问题吗?有什么方法可以将正则表达式更改为在Android Studio中不会失败的类似正则表达式吗?我是否缺少某些设置?

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?

推荐答案

Android Pattern文档\G列为受支持的运算符:

Android Pattern documentation lists \G as a supported operator:

\G   上一场比赛的结束

\G    The end of the previous match

因此,这听起来像是Android Studio的错误.

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()

模式匹配:

  • (?<=[NE]\d{0,100})-紧靠NE以及0到100位数字的位置
  • \d{2}-两位数字
  • (?=\d*$)-在字符串末尾跟0或多个数字.
  • (?<=[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.

这篇关于Android Studio Kotlin正则表达式与预期不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆