0

The goal is I am reading in a text file and finding certain words to replace. It will then replace the words and output a new text file that has the words replaced. My code works good for single words, but if I try to replace a phrase with a space, it doesn't work. What I have is a HashMap that contains what I need to search for in the file.

 HashMap<String, Integer> hm = new HashMap<>(); hm.put("null",0); hm.put("max",1); hm.put("Do not repeat",2); hm.put("names",3); 

I then iterate through the HashMap and replace the strings with the word if the file contains it.

 for (String key : hm.keySet()) { String check = key; System.out.println(check); text = text.toLowerCase(Locale.ROOT).replaceAll(check, "WRONG"); } String new = text; 

This isn't working if I have a space in the words like for "Do not repeat". How can I get this to work for phrases and not just single words? It completely skips over the phrases and outputs the new file with only the single words replaced.

5
  • 2
    It's not the spaces, it's the uppercased D, no? Commented Jan 25, 2021 at 19:48
  • 1
    BTW, if you're wanting to replace the literal string, you should consider quoting it, e.g. Pattern.quote(check), to avoid surprising things with metacharacters. Or just use replace, ofc. Commented Jan 25, 2021 at 19:50
  • 1
    Thank you! I feel so silly! Do you happen to know a way to do this without turning the text file to lowercase? Commented Jan 25, 2021 at 19:52
  • Do you mean, how to do it case-insensitively? Commented Jan 25, 2021 at 19:52
  • Yeah, I would like to check without having to change all the letters in the file to lowercase! Commented Jan 25, 2021 at 19:53

1 Answer 1

2

It's not to do with the spaces, it's because of the upper-cased D.

text.toLowerCase(Locale.ROOT) 

will make a string containing only lower-cased letters, so "Do not repeat" will not be found in it.

You can make replaceAll case insensitive by passing the appropriate flag:

text = text.replaceAll("(?i)" + check, "WRONG"); 

Note that you might run into problems with metacharacters in the strings you are searching for. If you might include things with e.g. periods (.), you should quote check:

text = text.replaceAll("(?i)" + Pattern.quote(check), "WRONG"); 

Also, because you're not considering word boundaries, you might run into the Scunthorpe problem.

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

1 Comment

Perfect! Exactly what I wanted to learn!. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.