Search code examples
javaregexstringreplacereplaceall

Code Not Producing Expected Results


I'm fairly new to Java. I am coding a Symmetric-Key Encryption Program that encrypts a string entered at command line. For some reason, this section is not giving me the results I was looking for:

    String[] replaceNum = {
        " 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 ", 
" 10 ", " 11 ", " 12 ", " 13 ", " 14 ", " 15 ", " 16 ", " 17 ", " 18 ", 
" 19 ", " 20 ", " 21 ", " 22 ", " 23 ", " 24  ", " 25 ", " 26 ", " 27 ",
" 28 ", " 29 ", " 30 ", " 31 "};

    String[] replaceChar = {
        " A ", " B ", " C ", " D ", " E ", " F ", " G ", " H ", " I ",
" J ", " K ", " L ", " M ", " N ", " O ", " P ", " Q ", " R ", " S ",
" T ", " U ", " V ", " W ", " X  ", " Y ", " Z ", " . ", " //, ", 
" //! ", " //? ", " _ "};


    message = message.toUpperCase();
    message = message.replaceAll(" ", "_");
    message = " " + message.replaceAll(".(?=.)", "$0 ") + " ";

    for (int x=0; x<=30; x++) {
        message = message.replaceAll(replaceChar[x], replaceNum[x]);
    }

Basically, I want to replace the characters in the message string with numbers from 1 to 31. When I compile, the output will be something like some# 27 some# 27 some# 27... It worked fine when I used 31 lines of

message = message.replaceAll("character", "number");

Also, if I include any punctuation, I get an error. Not very familiar with "//", and don't really understand "Regex". Please help!


Solution

  • it's supposed to be \\? or \\! because \\ is used to escape special character like ? and ! in regex and treat them like normal character so you want to change it to \\ instead of //