https://kotlinlang.org logo
#getting-started
Title
# getting-started
w

Waqas Tahir

01/06/2022, 8:49 PM
Hi I need to convert a function with java pattern class to kotlin regex class but my functions not returning the same output (
matchesList
) Code With Pattern Class
Copy code
val matcher = pattern.matcher(string)
val matchesList = mutableListOf<String>()
while (matcher.find()) {
    matchesList.add(matcher.group(0))
    if (!isGlobal) {
        var i : Int = 1
        val iEnd : Int = matcher.groupCount()
        while (i <= iEnd) {
            matchesList.add(matcher.group(i))
            i++
        }
    }
}
return matchesList
Code With Regex Class (not working)
Copy code
var result : MatchResult? = regex.matchEntire(string) ?: return mutableListOf()
val matchesList = mutableListOf<String>()
while(result!=null){
    result.groups[0]?.value?.let { matchesList.add(it) }
    if(!isGlobal){
        var i = 1
        while(i <= result.groups.size){
            result.groups[i]?.value?.let { matchesList.add(it) }
            i++
        }
    }
    result = result.next()
}
return matchesList
e

ephemient

01/06/2022, 9:00 PM
matchEntire
!=
matcher.find
1
you can use
Regex.find
similar to the Java code, or better yet, simply
Copy code
for (matchResult in regex.findAll(string)) {
    ...
}
👍 1
w

Waqas Tahir

01/06/2022, 9:24 PM
Still can't' do it
Copy code
val myMatchesList = mutableListOf<String>()
var startIndex = 0
var matchResult = regex.find(string,startIndex)
while(matchResult!=null){
    var i = 1
    while(i<=matchResult.groups.size) {
        matchResult.groups[0]?.value?.let { myMatchesList.add(it) }
        if(!isGlobal){
            matchResult.groups[i]?.value?.let { myMatchesList.add(it) }
        }
        i++
    }
    startIndex = matchResult.range.last
    matchResult = regex.find(string,startIndex)
}
did it , needed to replace last + 1 and change i back to 0 and use less than operator
e

ephemient

01/06/2022, 9:35 PM
no need for all that, just do
Copy code
val myMatchesList = regex.findAll(string).flatMap { if (isGlobal) listOf(it.value) else it.groupValues }.toList()
or something similar (not sure why you're adding groups[0] repeatedly)
w

Waqas Tahir

01/06/2022, 9:46 PM
do you know appendTail and appendReplacement equivalent in kotlin regex that I could use , I need to replace those !
The above code is working
Thanks for the help
e

ephemient

01/06/2022, 9:50 PM
do you really need
append*
? in kotlin you'd just use
Regex.replace
normally
👍 1
5 Views