I am new to regular expression, can any one tell me what is the best option to check if a string is containing only alphanumeric characters and why?
value.matches("^[a-zA-Z0-9]*$");
or value.matches("\\w+");
Asked
Active
Viewed 89 times
0
-
What means *best option* ? Best in what? – Jens May 02 '17 at 07:18
-
`\w` is just a predefined character class, the same as writing `[a-zA-Z_0-9]` so your both regex are not really the same, but the the difference has nothing to do with your question I guess – xander May 02 '17 at 07:19
-
@Jens by "best" i mean which is more appropriate and which will you prefer out of both and why ? – Vicky May 02 '17 at 07:21
-
i would prefer a mix of both: `value.matches("^\\w+$");` – Jens May 02 '17 at 07:23
-
Most appropriate? Please specify your criteria for "appropriateness". (And try to give an objective, non-circular specification.) Asking for which we prefer is asking for an opinion, and Questions that ask for opinion-based answers are off-topic. – Stephen C May 02 '17 at 07:23
-
define alphanumeric at first – Stimpson Cat May 02 '17 at 07:26
-
@xander : so if I write ("^[a-zA-Z_0-9]*$") and I have other "\w " then will it be still the same or the "start and end" condition will make some difference in the first case here? – Vicky May 02 '17 at 07:27
-
Hint: look up the definitions in the javadocs for the `Pattern` class, and you make up your mind which is *correct* for what you are actually trying to achieve. Like ... depending on what do *you* mean by alphanumeric ... – Stephen C May 02 '17 at 07:31
-
@Gaurav the start and end makers make a difference of course, but as I said `\w` is just `[a-zA-Z_0-9]` in short. but "\\w+" will match a string like " ab12%&" because it contains `\w`, so you needd to use "^\\w+$" as @Jens said to check the whole string. Just remember if you leave `^` and `$` out it essentially is a contains check. – xander May 02 '17 at 07:32
-
@xander Thanks for the answer, now got the difference. Actually I wanted a string which can have all the alphanumeric characters except punctuation so here what I am going to use is.Pattern p = Pattern.compile("\\p{Punct}"); Matcher m = p.matcher(value); if(value.matches("^\\w+$") && !m.find()){ return true; } – Vicky May 02 '17 at 08:56
-
@Gaurav ok but if `value.matches("^\\w+$")` returns true it can never contain any punctuation characters in the first place. So it's unnecessary or I don't get it. – xander May 02 '17 at 09:04
-
@xander yes you are right, I checked it just now. Thank you again. – Vicky May 02 '17 at 09:12