Reputation: 617
I have a requirement to ensure that the string has only alphanumeric or a set of characters like + ( ) , ' . - = I tried like
String regex = "([a-zA-Z0-9]+)|([\\'|\\()|\\+|\\,|\\-|\\.|\\="]+)";
System.out.println("Regex : " + regex);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println("Match");
} else {
System.out.println("Not Matching");
}
Bt it is not working, Can anyone help me please
Thanks in advance
Upvotes: 1
Views: 8749
Reputation: 124215
It seems that you have compilation problem in
String regex = "([a-zA-Z0-9]+)|([\\'|\\()|\\+|\\,|\\-|\\.|\\="]+)";
because you have "
before ]
which ends String. If you want to include "
in that set of characters you need to escape it \"
. If not then just remove it from your regex.
Also |
inside [...]
will make it normal character, not OR operator so you don't need to use it here. BTW only special character that need escaping in your [...]
is -
.
Try maybe
String regex = "([a-zA-Z0-9]+)|(['()+,\\-.=]+)";
or if you want to include "
in special characters
String regex = "([a-zA-Z0-9]+)|(['()+,\\-.=\"]+)";
Upvotes: 0
Reputation: 369044
Use following regular expression:
^[-+=(),'.a-zA-Z0-9]+$
If you want allow zero-length string, replace +
with *
:
^[-+=(),'.a-zA-Z0-9]*$
Upvotes: 3
Reputation: 544
It looks like it will not match a whole string containing a mix of alphanumerics and symbols because of the OR in the middle.
e.g. it wont match abcABC()+, but will match abcABC and will match ()+
Try:
([a-zA-Z0-9\\'\\(\\+\\)\\,\\-\\.\\=]+)
Hope this helps!
Upvotes: 4