是否有一个正则表达式来切换字符串中的字符大小写? [英] is there a Regex to toggle Character case in a String?

查看:95
本文介绍了是否有一个正则表达式来切换字符串中的字符大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串

I have a string like

var str = "AbCdEfGhIj"

我要切换每个字符的大小写,即

that i want to toggle each character casing, that is,

将其转换为var str = "aBcDeFgHiJ"

我目前正在下面使用此代码

i am currently using this code below

val bytes = "HEllo WoRLd".toByteArray()
// Swap upper and lower case letters.
    for (i in bytes.indices) {
        if (bytes[i] >= 'A'.toByte() && bytes[i] <= 'Z'.toByte())
            bytes[i] = ('a'.toInt() + (bytes[i] - 'A'.toByte())).toByte()
        else if (bytes[i] >= 'a'.toByte() && bytes[i] <= 'z'.toByte())
            bytes[i] = ('A'.toInt() + (bytes[i] - 'a'.toByte())).toByte()
    }
 System.out.print(String(bytes)) // heLLO wOrlD

想知道是否有正则表达式可以做到这一点

Wondering if there's a regex that can do this

推荐答案

正如评论所说,正则表达式用于匹配而不是更改.

As the comments say, regexes are for matching, not altering.

但是问题中的代码可以改进;对于非ASCII字符,它将失败(并且不必要地复杂).这是一个更优雅的版本,作为String上的扩展功能:

But the code in the question can be improved; it will fail for non-ASCII characters (and is unnecessarily complex).  Here's a more elegant version, as an extension function on String:

fun String.swapCase() = map {
    when {
        it.isUpperCase() -> it.toLowerCase()
        it.isLowerCase() -> it.toUpperCase()
        else -> it
    }
}.joinToString("")

println("HEllo WoRLd".swapCase()) // heLLO wOrlD

这篇关于是否有一个正则表达式来切换字符串中的字符大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆