简体   繁体   English

java字符串替换所有特定字符串后的第一个字符为小写

[英]java string replaceall first character after certain string to lower case

I have a requirement to replace all the character within a string to lower case if it is followed by some string like "is". 我要求将字符串中的所有字符替换为小写(如果后跟“ is”之类的字符串)。

For example: 例如:

String a = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";

it should get converted to 它应该转换为

"name=xyz,salaried=Y,address=abc,manager=N,salary=1000"

I am not very good at regular expression but I think can use it to achieve the required output. 我不太擅长使用正则表达式,但我认为可以使用它来实现所需的输出。 It will be great if someone can help me out. 如果有人可以帮助我,那就太好了。

Your solution requires basic understanding of String and String methods in java. 您的解决方案需要对Java中的String和String方法有基本的了解。 Here is one working example. 这是一个工作示例。 Although, it might not be the most efficient one. 虽然,它可能不是最有效的一种。 NOTE:- YOU ASKED FOR A REGEX SOLUTION.BUT THIS IS USING PURE STRING METHODS 注意:- 您询问了正则表达式解决方案,但这是使用纯字符串方法

public class CheckString{
    public static void main(String[] ar){
        String s = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";
        String[] arr = s.split(",");
        String ans = "";
        int i = 0;
        for(String text : arr){
            int index = text.indexOf("=");
            String before = text.substring(0,index).replace("is","").toLowerCase();
            String after = text.substring(index);
            if(i!=(arr.length-1)){
                ans += before + after + ",";
                i++;
            }
            else{
                ans += before + after;  
            }
        }
        System.out.println(ans);
    }
}

Try this. 尝试这个。 first match the string and replace in a loop 首先匹配字符串并循环替换

    String a = "name=xyz,isSalaried=Y,address=abc,isManager=N,salary=1000";

    Matcher matcher = Pattern.compile("is(.*?)=").matcher(a);//.matcher(a).replaceAll(m -> m.group(1).toLowerCase());

    while (matcher.find()) {
        String matchedString = matcher.group(1);

        a = a.replace("is"+matchedString,matchedString.toLowerCase());
    }
    System.out.printf(a);

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

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