-1

I have set of some characters as below :

[A-Za-z0-9/-?:().,’+#=! ” %& * <>; {@\r\n] 

I have to write a program in java to make sure input is not having any character out of this set and if they do, I have to replace them with spaces.

How can I achieve this ? Only Java 6 please.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    Also, when you say "out of this set", do you mean you want to replace characters that are _in_ this set, or that are _not in_ this set? – tobias_k Jun 16 '16 at 11:37

2 Answers2

1

String str = str.replaceAll("([^A-Za-z0-9/\\-?:\\(\\)\\.,’\\+#=! \\” %& \\* <>; \\{@\\r\\n])", " ")

Basically, if you have a set that is not in "abc", you use the caret to negate the group --> [^abc]

Here is a great guide to better using regex: http://www.regular-expressions.info/

And if you want to test, here is another great tool: https://regex101.com/

engineer14
  • 607
  • 4
  • 13
0

Do the following. [A-Z] matches anything in the range while [^A-Z] matches anything not in the range. This will work in Java.

String out = input.replaceAll("[^A-Za-z0-9\\/\\-?:().,\'+#=!\"%&*<>;{@\\r\\n]", " ");
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58