Mohammad Hasan
Mohammad Hasan

Reputation: 71

Regex - using replaceAll() to replace a word but to maintain the case

I started learning regex recently. Here I have a code that takes a word. If it has "as" in it, it replaces/appends according to the conditions.

Conditions :

  1. If "as" is in the beginning of the word (like astronaut) then delete the word "as" (the result will be "tronaut").

  2. If "as" is in the end of the word (like has) then add k to it; leave a space; append a "?" (like "hask ?").

    import java.util.Scanner;
    import java.util.regex.*;
    
    public class test {
        public static void main(String args[])
        {
            System.out.print("Enter a string : ");
            Scanner console = new Scanner(System.in);
            String input = console.nextLine();
            Pattern frontPattern,backPattern;
            Matcher matcher;
            frontPattern = Pattern.compile("^(?i)as");
            matcher = frontPattern.matcher(input);
            if(matcher.find())
            {
                String replaced = matcher.replaceAll("");
                System.out.println(replaced);
            }
            backPattern = Pattern.compile("(?i)as$");
            matcher = backPattern.matcher(input);
            if(matcher.find())
            {
                String replaced = input.replaceAll("(?i)(as)","$1k ?");
                System.out.println(replaced);
            }
        }
    }
    

Problem that i face is.. if the input is "LAS" then the desired output is "LASK ?" but I dont know how to maintain the case. It prints "Lask ?"

Upvotes: 1

Views: 79

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174826

Do condition checking for whether the matched string is lowercase or not.

backPattern = Pattern.compile("(?i)as$");
matcher = backPattern.matcher(input);
if(matcher.find())
{
   if(matcher.group().isLowerCase()) {
    String replaced = matcher.replaceAll("ask ?");
    System.out.println(replaced);}
    else{
    String replaced = matcher.replaceAll("ASK ?");
    System.out.println(replaced);}
}

Upvotes: 2

Related Questions