Search code examples
javareplaceall

Java replaceall regex issue


I am trying to add a letter to each consonant, the issue I do have is that I cannot figure out how I should add different for lowercase and uppercase.

Can I use double regex for this? in that case, how?

    import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
//      skapar en scanner
        Scanner sc = new Scanner(System.in);
        System.out.print("Skriv en rad text: ");
//      tar användarens input och översätter den till rövarspråket.
        String input = sc.nextLine();   
        System.out.println(input.replaceAll("([bcdfghjklmnpqrstvwxz])", "$1o$1"));
    }
}

Solution

  • I think your question is a extracted excerpt for a larger program.

    import java.util.Scanner;
    
    public class ScratchJava {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Skriv en rad text: ");
            String input = sc.nextLine();
            String intermediate = input.replaceAll("([bcdfghjklmnpqrstvwxz])", "$1o$1");
            System.out.println(intermediate.replaceAll("([BCDFGHJKLMNPQRSTVWXZ])", "$1X$1"));
        }
    }
    

    You can replace in two passes one for lower case other for upper case.

    I couldn't find a method in standard library which would replace in same pass based on condition of match, though that would be much faster for a large input. Consider writing one yourself if you hit performance issues.