1

Can anybody please tell me what's wrong with this regexp

"^[a-zA-Z0-9 -\\/_&()']*$"

I expect this to accept only values like abc123/-_'s but I'm not sure why it's even accepting ABC

But it's not accepting double quotes in it.

Here is my code:

public static final Pattern 

    PATTREN = Pattern.compile("^[a-zA-Z0-9 -\\/_&()']*$");
    Matcher m = PATTREN .matcher("ABC\"");
    return m.matches();
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
  • 1
    **don't use unescaped `-` at the middle of character class.** Use the hyphen at the start or at the end of char class. – Avinash Raj Mar 09 '15 at 07:36
  • Oh you got it right :) Thanks a lot @Avinash Raj. I changed my pattren to "^[a-zA-Z0-9 \\/_&()'-]*$" and its proper now. can you please brief how does the meaning differ with placement of "-" in the pattren? Thanks again. – Mujahid Pasha Mar 09 '15 at 07:42
  • read the second answer in the above link. – Avinash Raj Mar 09 '15 at 07:46

2 Answers2

0

The pattern says, A-Z, so why do you think it would not allow uppercase characters?

You are defining a character class, using []; and anything between the square brackets is seen as "valid" character. So if you dont want uppercase letters, then remove A-Z from the [].

Btw: although it is not supporting Java, you might want to play with https://regex101.com/

That is a great site to "practice" regular expressions; and it isnt too hard to "convert" regexes from other languages to Java.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I'm okay with uppercase as its allowed and its valid too but i was specific about double quotes " which is not valid according to my reqexp. – Mujahid Pasha Mar 09 '15 at 07:39
0

I believe this is what you want

  • Only character that needs escaping within [] is the hyphen - which has special meaning. Everything else is literal, even brackets, slashes etc. which usually have meaning.

  • No need for start and end markers

  • You can use Pattern.CASE_INSENSITIVE flag in pattern rather than added extra complexity via A-Za-z Code

Example

Pattern pattern = Pattern.compile("[a-z0-9\\-/_&()']*", Pattern.CASE_INSENSITIVE);
System.out.println(pattern.matcher("abc123/-_'s").matches());
System.out.println(pattern.matcher("ABC\"").matches());
Adam
  • 35,919
  • 9
  • 100
  • 137