1

How would I replace all that is not stored in the variable guess in the current Pattern with a "-"? The guess will change with different method calls. I want to replace anything that is not the char guess(in this case => 'e') with a "-".

String word = "ally";
char guess = 'e';
String currentPattern = word.replaceAll("[^guess]", "-");

Obviously, this does not work.

6
  • 3
    That is a Java question. Not related to Regex at all :) Commented Feb 21, 2013 at 7:54
  • Sorry, I am new on here:) Commented Feb 21, 2013 at 7:58
  • You must add guess as a variable as jlordo says. Anyway I had a similar question some time back: stackoverflow.com/questions/14932510/… Commented Feb 21, 2013 at 8:10
  • replaceAll can get a regexp in it's arguments... so it's a regexp related question Commented Feb 21, 2013 at 8:14
  • @ben75: It might be related to regex, but the question basically is how do I insert variable content into a string, which is basic java, nothing else. Commented Feb 21, 2013 at 8:18

4 Answers 4

4

You almost have it. Use String concatenation:

String currentPattern = word.replaceAll("[^" + guess + "]", "-");

This approach only works if you don't have regex metacharacters within guess, which need to be escaped within character classes. Otherwise a PatternSyntaxException will be thrown.

This question shows that in your case, where you only add a char to your character class, a PatternSyntaxException won't happen even if you don't escape anything.

Sign up to request clarification or add additional context in comments.

4 Comments

But this will replace the word when the characters are interchanged as well right? I mean if the word = "abcdfeghijklmnop" and out put will be same for when the guess = "ghij" and guess = "jihg".
@NamalFernando: guess is a char, so it is always only 1 character.
Ooops! missed it. My Bad! :)
Thank you! In this case, I will never have regex metacharacters within guess.
0

You are almost there, just use + concatenation operator to concatenate guess with the regex part.

            String word = "ally";
        char guess = 'e';
        String currentPattern = word.replaceAll("[^"+guess+"]", "-");
        System.out.println(currentPattern);

Comments

0

You need to include the variable explicitly in the regex string:

String word = "alely";
char guess = 'e';
System.out.println(word.replaceAll(String.format("[^%s]", guess), "-"));

Comments

0

Turn it into a method?

public String replaceAllExcept( String input, char pattern ) {
    return input.replaceAll( "[^" + pattern + "]", "-" );
}

System.out.println( replaceAllExcept( "ally", 'e' );
System.out.println( replaceAllExcept( "tree", 'e' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.