1

I my java app, I have a following character sequence: b"2 (any single character, followed by a double quote followed by a single-digit number)

I need to replace the double quote with a single quote character. I'm trying this:

Pattern p = Pattern.compile(".\"d");
Matcher m = p.matcher(initialOutput);
String replacement = m.replaceAll(".'d");

This does not seem to do anything.

What is the right way of doing this?

2
  • Check this Commented Jan 12, 2018 at 2:23
  • If by any single character you mean any letter, then the accepted answer is not correct since . matches any char, not a letter. Please clarify if you need more help with this. Commented Jan 12, 2018 at 7:42

1 Answer 1

1

First off, d represents a literal character. You're looking for \d, which represents a numeric digit.

The other issue is that you're replacing variable characters with the string literal ".'d". One solution is to capture the variable portions and reference them in the replacement:

String replacement = initialOutput.replaceAll("(.)\"(\\d)", "$1'$2");

Another approach is to use lookarounds to check the surrounding characters without actually matching them for replacement:

String replacement = initialOutput.replaceAll("(?<=.)\"(?=\\d)", "'");
Sign up to request clarification or add additional context in comments.

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.