我有一个静态方法,它在目标文本上找到匹配的文本,但它对相同的输入返回不同的结果,Junit
测试中的结果和Android
运行时的结果是不同的。
private const val REGEX = "GE[a-zA-Z0-9]{2}\\s?([a-zA-Z0-9]{2})([0-9]{2}\\s?)([0-9]{4}\\s?){3}([0-9]{2})\\s?"
private val PATTERN: Pattern = Pattern.compile(REGEX, Pattern.MULTILINE or Pattern.CASE_INSENSITIVE)
fun find(text: String): List<String> {
val textFormatted = text.replace("\\s".toRegex(), "")
val list = ArrayList<String>()
val matcher = matcher(textFormatted)
when {
matcher.matches() -> {
list.add(textFormatted)
}
matcher.find() -> {
val partitions = findGroupMatches(matcher)
list.addAll(partitions)
}
}
return list
}
private fun findGroupMatches(matcher: Matcher): List<String> {
val partitions = mutableListOf<String>()
for (i in 0 until matcher.groupCount()) {
val partition = matcher.group(i)
if (partition != null && PATTERN.matcher(partition).matches()) {
partitions.add(partition.replace("\\s".toRegex(), ""))
}
}
return partitions
}
神奇的事情就发生在这里
On JVM tests, it returns emptyList
@Test
fun `find with not valid text returns emptyList`(){
val targets = PatternUtils.find("GE03TB 7433311450666666300008")
assertTrue(targets.isEmpty()) // success
}
PatternUtils.find("GE03TB 7433311450666666300008") on Android inside `onCreate()` returns 1 size list("GE03TB743331145066666") //
为什么会这样?有什么问题吗?还是我漏掉了什么?
1条答案
按热度按时间35g0bw711#
原因是Oracle和Google的
Pattern.java
实现不同。为了能以类似的方式工作,我不得不创建新的
Matcher
,而不是重用它。(Matcher.java有一些方法会产生副作用)