2

i am searching for a regular expression i can use to check if a user input contains special characters in a specified list.

Here are the special characters not allowed by using a regular expression i tried to write: ^[`~!@#$%^&*()_+={}\[\]|\\:;“’<,>.?๐฿]*$

i went to https://regex101.com/ and i was expecting the following input to match but did it not why:

127 elmer road ??<>()

so in android java (but an be any ) i wrote the following function but it also always returns true . how can i filter all these special characters . I want a function that returns true if a given string does NOT match.

  public boolean isValid( EditText et) {
            String string = et.getText().toString();
            boolean isValid = true;

             final Pattern sPattern
                    = Pattern.compile("^[`~!@#$%^&*()_+={}\\[\\]|\\\\:;“’<,>.?๐฿]*$");

            isValid=  !sPattern.matcher(string).matches();


            return isValid;
        }

update: i tried the following also:

enter image description here

5
  • Your regex expects a start of string, a single character in the list, and then the end. Try something like this: ^.*[~!@#$%^&()_+={}[\]|\:;“’<,>.?๐฿].*$ Note, you need to escape the ]. Commented Nov 10, 2017 at 6:33
  • when i tried that i got an exception . but also the IDe gave a complaint of" Pattern.compile("^.*[~!@#$%^&()_+={}[]|\\:;“’<,>.?๐฿].*$"); unclosed character class". this was at the very end after the $. it let me run the program but i got the following exception: java.util.UnknownFormatConversionException: Conversion: ^
    – j2emanue
    Commented Nov 10, 2017 at 6:37
  • Note my edit - escape the ] Commented Nov 10, 2017 at 6:37
  • Why do you have ^ and $ in your regex?
    – melpomene
    Commented Nov 10, 2017 at 6:38
  • can you tell me what i should do then ? i mean i was trying to do the "NOT" of that. really i just need . a regular espression that removes all these special chars. and im using the *$ to say that zero or more characters can follow.
    – j2emanue
    Commented Nov 10, 2017 at 6:44

1 Answer 1

5

I want a function that returns true if a given string does NOT match.

You can negate the character set. (Note the ^ symbol within the square brackets). This will return true for strings that don't contain any of these special characters.

^[^`~!@#$%^&*()_+={}\[\]|\\:;“’<,>.?๐฿]*$

https://regex101.com/r/CqtqoK/1

Not the answer you're looking for? Browse other questions tagged or ask your own question.