0

I need to check if a JAVA string which we send to commzgate(3rd party) as SMS but our SMS fails because our string is containing some invalid/non-readable characters which I need to check first. Basically i need to put a regular expression check in java to validate if my string contains following characters or not :-

€ [ \ ] ^ { | } ~

Any suggestions! Moreover when I try to put these characters in my java file, it does not save and alerts for non-utf8 character message in eclipse, so everytime i have to remove € and save. Is that so my validation is not complete. Thanks

Ross Taylor-Turner
  • 3,687
  • 2
  • 24
  • 33
Vinod Kumar
  • 665
  • 3
  • 13
  • 31
  • 4
    [`Java` != `JavaScript`](http://stackoverflow.com/a/245069/1393766), read tags description before you use them. – Pshemo Nov 20 '14 at 16:02
  • 2
    A safer thing yet would be to check if the char is valid rather than invalid. In other words check that it is alphabetical or a number or one of the 30 or so symbols you wish to allow – Michael Goldstein Nov 20 '14 at 16:09

3 Answers3

1

You appear to have included an answer in your question - you can use a regular expression to check for these characters and replace/remove them as required. As you are hitting a problem with Eclipse on a non-UTF-8 character (the Euro symbol) you could instead use the unicode character U+20AC (which should be it).

regular expression java

Community
  • 1
  • 1
Ross Taylor-Turner
  • 3,687
  • 2
  • 24
  • 33
0

The regexp is /[€\[\]\{\}\~]/g You can do simpler but this one works

For example in js

var a = "€[]{}^|~"
var reg = /[€\[\]\{\}\~|^]/g
a.replace(reg, "") //output ""
Waxo
  • 1,816
  • 16
  • 25
0

Use simply:

^[^€\\[\\]\\^{|}~\\\]*$
// €  [  ]  ^{|}~  \    < literals

Which matches the start and end of string, any characters (or none) provided they aren't in the (escaped) character class. The ^ inside the character class here indicates that it should not match.

Note the double-escaped characters because Java requires literal characters to be escaped as well.

brandonscript
  • 68,675
  • 32
  • 163
  • 220