简体   繁体   English

在 Groovy 语言中如何根据字符串中的值和位置替换字符串中的字符

[英]In Groovy Language How to replace a character in a string based on the value and position in the string

I am looking to amend the values of a string IF certain positions within a string are certain values for example I have a postcode L65 OBH and I need to do the following:如果字符串中的某些位置是某些值,我希望修改字符串的值,例如我有一个邮政编码 L65 OBH,我需要执行以下操作:

(1) (1)

If the 1st value in the first section of the string (split by white space) = L it needs to be changed to T. This would then give:如果字符串第一部分中的第一个值(由空格分割)= L,则需要将其更改为 T。这将给出:

T65 OBH T65 OBH

(2) (2)

Then if the 2nd value in the first section of the string (split by white space) = 6 it needs to be changed to 7. This would then give:然后,如果字符串第一部分中的第二个值(由空格分割)= 6,则需要将其更改为 7。这将给出:

T75 OBH T75 OBH

(3) (3)

Then if the 1st value in the second section of the string (split by white space) = O it needs to be changed to 2. This would then give:然后,如果字符串的第二部分中的第一个值(由空格分割)= O,则需要将其更改为 2。这将给出:

T75 2BH T75 2BH

(4) (4)

Then if the 3rd value in the second section of the string (split by white space) = H it needs to be changed to P. This would then give:然后,如果字符串第二部分中的第三个值(由空格分割)= H,则需要将其更改为 P。这将给出:

T75 2BP T75 2BP

I'm assuming that I need to use replaceall and a number of IF statements but I am struggling to work this out, particularly how to split the 2 different parts of the postcode out treat them as separate enteties....can anyone help please我假设我需要使用 replaceall 和一些 IF 语句,但我正在努力解决这个问题,特别是如何将邮政编码的 2 个不同部分拆分为单独的实体......任何人都可以帮忙吗

I'd write a helper method for the replacement rules:我会为替换规则编写一个辅助方法:

def postcode = 'L65 0BH'

def (first, second) = postcode.split(/\s+/)

def replaceIf(String token, int position, String match, String replacement) {
    (0..<token.length()).collect { index ->
        if(index == position && token[index] == match) {
            replacement
        }
        else {
            token[index]
        }
    }.join()
}

first = replaceIf(first, 0, 'L', 'T')
first = replaceIf(first, 1, '6', '7')
second = replaceIf(second, 0, '0', '2')
second = replaceIf(second, 2, 'H', 'P')

assert "$first $second" == 'T75 2BP'
def strVal= "L65 OBH"
strVal.replaceFirst(/^L/, "T")

def strVal1= "L65 OBH"
strVal1.replaceFirst(/^6/, "7")

and so on using the same replaceFirst() method等等使用相同的replaceFirst()方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM