smeeb
smeeb

Reputation: 29537

Iterating a string and checking regexes in Groovy

Groovy here. I'm trying to iterate over the characters in a string and add them to another string with the following logic:

My best attempt has not worked out so great:

// We want to convert this to: 'Well Hello There'
String startingStr = 'WellHelloThere'
String special = ''
startingStr.each { ch ->
    if(ch == ch.toUpperCase() && startingStr.indexOf(ch) != 0) {
        special += " ${ch}"
    } else {
        special += ch
    }
}

More examples:

Starting Str     |      Desired Output
======================================
'wellHelloThere' |      'well Hello There'
'WellHello9Man'  |      'Well Hello 9 Man'
'713Hello'       |      '713 Hello'

Any ideas where I'm going awry here?

Upvotes: 1

Views: 103

Answers (2)

Michael Easter
Michael Easter

Reputation: 24498

Consider the following: (see comment about desired output for '713 Hello' and the stated rules)

String s1 = 'wellHelloThere'
String s2 = 'WellHello9Man'
String s3 = '713Hello'

def isUpperCaseOrDigit = { it ==~ /^[A-Z0-9]$/ }

def convert = { s ->
    def buffer = new StringBuilder()

    s.eachWithIndex { c, index ->
        def t = c 

        if ((index != 0) && isUpperCaseOrDigit(c)) {
            t = " ${c}"
        }

        buffer.append(t)
    }

    buffer.toString()
}

assert "well Hello There" == convert(s1)
assert "Well Hello 9 Man" == convert(s2)
// this is different than your example, but conforms
// to your stated rules:
assert "7 1 3 Hello" == convert(s3)

Upvotes: 0

Saurabh Gaur
Saurabh Gaur

Reputation: 23815

Try as below :-

String regex = "(?=\\p{Upper})|(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"

String s1 = 'wellHelloThere'
String s2 = 'WellHello9Man'
String s3 = '713Hello'

assert s1.split(regex).join(" ") == "well Hello There"
assert s2.split(regex).join(" ") == "Well Hello 9 Man"
assert s3.split(regex).join(" ") == "713 Hello"

Upvotes: 1

Related Questions