smeeb smeeb - 4 months ago 9
Groovy Question

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:


  • If the character is a lowercase character ([a-z]), then just add it to the other string as-is; but...

  • If the character is uppercase or it is a number ([0-9][A-Z]), then append a single whitespace to the other string, then add it to that other string (so,
    " ${theChar}"
    )


    • The exception to this is in the event that the first char in the string is either uppercase or a number, then we just add it to the other string, again, as-is


  • I can't use any 3rd party libs like Commons Lang/WordUtils, etc.



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?

Answer

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"
Comments