你可以使用 Kotlin 的 Regex 类来找出长字符串中所有指定字符串的出现位置,并返回它们的起始位置。下面是一个使用 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 函数接受两个参数:regexPatterninputStringregexPattern 是你要匹配的字符串 A,inputString 是长字符串 B。它使用 Regex 类将正则表达式编译成一个 Regex 对象,然后使用 findAll 函数找到所有匹配的结果。接着,我们遍历每个匹配结果,并将其起始位置添加到 occurrences 列表中。最后,返回包含所有起始位置的列表。

main 函数中,我们定义了要匹配的字符串 A 和长字符串 B,并调用 findOccurrences 函数来找到所有的 A,并打印出它们的起始位置。

Kotlin 正则表达式查找字符串所有匹配位置

原文地址: https://www.cveoy.top/t/topic/p6Mw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录