迭代字符串并检查Groovy中的正则表达式

时间:2016-08-02 10:49:38

标签: regex groovy

Groovy在这里。我正在尝试迭代字符串中的字符,并使用以下逻辑将它们添加到另一个字符串:

  • 如果字符是小写字符([a-z]),则只需按原样将其添加到另一个字符串;但是...
  • 如果字符大写或者是数字([0-9] [AZ]),则将一个空格附加到另一个字符串,然后将其添加到另一个字符串(所以," ${theChar}"
    • 异常,如果字符串中的第一个字符是大写字母或数字,那么我们只需将其添加到另一个字符串中,as-is
  • 我不能使用任何第三方库,如Commons Lang / WordUtils等。

我最好的尝试并没有那么好:

// 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
    }
}

更多例子:

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

我在这里出错的任何想法?

2 个答案:

答案 0 :(得分:1)

尝试如下: -

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"

答案 1 :(得分:0)

请考虑以下事项:(请参阅关于&#39; 713 Hello&#39;以及所述规则的所需输出的评论)

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)