2

I know this question has been asked many times on Stack Overflow but regex is too hard to understand.

What I tried:

String sentence = "The #{adjective} brown fox jumps over the lazy dog";
            String requierd_sentence = sentence.replaceAll("[{*.*}]", "quick");
            System.out.println(requierd_sentence);

Here in this sentence, adjectives are not at fixed position — they change with every new string/sentence. What I need to do is, replace the adjective with required string which is available in another column besides the sentence column. So fetching the string from column is OK, but regex matching is failing on many attempts.

What would be the correct regex for #{any string}?

  1. Sample output for above string would be = The quick brown fox jumps over the lazy dog.
  2. Another example input, All that #{adjective} is not gold should output All that glitters is not gold.

Now both sentences above have #{adjective} on different positions of the sentence, so I can't use split. I have to use a regex pattern.

2
  • Give sample input and output. It would make more sense than multiline explainations of the output expected. Commented Jun 17, 2014 at 5:22
  • Properly escape the [ and {: sentence.replaceAll("\\[\\{*.*}]", "quick");. Commented Jun 17, 2014 at 5:23

1 Answer 1

2

You can use this (see demo):

String replaced = your_original_string.replaceAll("#\\{[^}]*}", "quick");

How Does This Work?

  • The #\\{ matches the literal characters *{
  • The [^}]* negative character class matches any characters that are not a closing brace
  • The } matches a closing brace
  • We replace all of this with "quick"
Sign up to request clarification or add additional context in comments.

3 Comments

Superb! it worked, but explanation is not good. However, 3 cheers for the spirit, that you cared to give just not the answer but explanation also, so that people can learn. Can you explain it in better way.
@paul Completely rewrote the explanation. Does this work for you? Let me know. :)
Thanks, understood. Upvote for demo, its an excellent thing to learn regex.

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.