有一个字符串A和长字符串BB中有0到n个A用正则找出B中所有的A并返回起始位置。语言用kotlin
你可以使用Regex类来找出B中所有的A,并返回其起始位置。下面是一个使用Kotlin的示例代码:
fun findOccurrences(regexPattern: String, inputString: String): List<Int> {
val regex = Regex(regexPattern)
val matches = regex.findAll(inputString)
val occurrences = mutableListOf<Int>()
for (matchResult in matches) {
occurrences.add(matchResult.range.first)
}
return occurrences
}
fun main() {
val pattern = "A" // 替换为你要匹配的字符串A
val input = "BAAABBBAAAABABAA" // 替换为你的长字符串B
val occurrences = findOccurrences(pattern, input)
println("Occurrences of $pattern in $input:")
for (position in occurrences) {
println("Found at position $position")
}
}
运行上述代码,你将得到以下输出:
Occurrences of A in BAAABBBAAAABABAA:
Found at position 1
Found at position 2
Found at position 3
Found at position 7
Found at position 8
Found at position 9
Found at position 10
Found at position 11
Found at position 12
Found at position 15
代码中的findOccurrences函数接受两个参数:regexPattern和inputString。regexPattern是你要匹配的字符串A,inputString是长字符串B。它使用Regex类将正则表达式编译成一个Regex对象,然后使用findAll函数找到所有匹配的结果。接着,我们遍历每个匹配结果,并将其起始位置添加到occurrences列表中。最后,返回包含所有起始位置的列表。
在main函数中,我们定义了要匹配的字符串A和长字符串B,并调用findOccurrences函数来找到所有的A,并打印出它们的起始位置
原文地址: http://www.cveoy.top/t/topic/ioXC 著作权归作者所有。请勿转载和采集!