-1

Sorry I could not find anything that works and hence I am asking this question. I have a basic string that could have feet("), inch(') or comma(,). All I want to do is identify those and escape them before further processing. Not having any luck with Regex, as you can tell I am not good with it yet. Need help. Thanks much!

  • Why do you want to escape them? Have you tried using `String#replace` method? – anubhava Oct 14 '14 at 21:57
  • What do you mean by "Not having any luck with Regex...?" Do you mean you tried \' and your regular expression failed? Have you tried double backslashes to escape? – MarsAtomic Oct 14 '14 at 22:12
  • 1
    It doesn't look like you have any code, so maybe that's the problem. – l'L'l Oct 14 '14 at 22:18
  • The prime symbol is used for feet, and double prime for inches. They are often represented in ASCII with single and double quotes. You have them backwards in your question. – David Conrad Oct 14 '14 at 22:27

1 Answers1

0

Someone hinted at it in your comments, but its not entirely correct since String#replace only takes a single character, and you want to provide more than one for the replacement.

Say you have some function foo() that returns some regular expression that isn't escaped properly, with respect to the "\"" char, or the "\'" char:

String regexp = Bar.foo();
regexp = regexp.replaceAll("(\\\"|\\\')", "\\\\$0");
Pattern yourPatternName = Pattern.compile(regexp);

A little explanation: In Java, you need to escape certain special characters, such as n to mean newline ('\n'), or t to mean tab ('t'). Since you are already escaping them, they are no longer the literal characters '\' + 'n', for example. So, you need to escape them a second time, so that way when the regular expression is compiled, Pattern#compiler will see the two characters "\n" rather than the single character, which is the newline. To escape the '\n' character, you need to, of course, place in a new '\' character. Since we are doing a java.lang.String, we need to still escape that slash one more time.

As for the comma, you don't need to escape that. You only need to escape special characters. For a list of the ones that Pattern recognizes, you can check here:

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

searchengine27
  • 1,449
  • 11
  • 26