Hi I need to convert a function with java pattern ...
# getting-started
w
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
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
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
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
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
do you really need
append*
? in kotlin you'd just use
Regex.replace
normally
👍 1