【问题标题】:Iterating a string and checking regexes in Groovy在 Groovy 中迭代字符串并检查正则表达式
【发布时间】:2016-08-02 10:49:38
【问题描述】:

这里很时髦。我正在尝试遍历字符串中的字符并将它们添加到具有以下逻辑的另一个字符串中:

  • 如果该字符是小写字符 ([a-z]),则只需将其按原样添加到另一个字符串;但是...
  • 如果字符大写或者它是一个数字([0-9][A-Z]),则将一个空格附加到另一个字符串,然后将其添加到另一个字符串(所以, " ${theChar}")
    • 例外是如果字符串中的第一个字符是大写或数字,那么我们只需将其添加到另一个字符串,同样,原样
  • 我无法使用任何第三方库,例如 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'

有什么想法我会在这里出错吗?

【问题讨论】:

  • 根据您的规则,我相信在第三种情况下所需的输出是 '7 1 3 Hello'。

标签: regex groovy


【解决方案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"

【讨论】:

    【解决方案2】:

    考虑以下几点:(请参阅有关“713 Hello”所需输出的评论和规定的规则)

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多