Reputation: 10747
I have a below peace of code :
Pattern p = Pattern.compile("^\\d|^\\W|^\\s");
Matcher m = p.matcher("stack overflow");
Can somebody explain the above regex pattern ? What it does ? I have to make it not allow spaces in between with the existing functionality .e.g. it should not allow "stack overflow " since it contains spaces .
EDIT
Below pattern I tried is working fine for me . Thanks all for your suggestion:
[a-zA-Z0-9_$#]
Upvotes: 1
Views: 282
Reputation: 19500
Your regular expression matches either a single digit, OR any single char that is NOT a word OR any single char that is a white space char.
Any of those three alternatives must start at the beginning of the subject because you have ^
in each alternation.
Based on your description, i think you want an expression like this:
^[\w#$]+$
Which will match anything containing one or more word characters [A-Za-z0-9_]
, hash #
, and dollar $
. Word characters do not include spaces, so this should work.
I've added anchors ^
and $
which ensure that it only matches the whole string (is this what you want?) If you just want it to match at the beginning as in your example, then remove the $
.
Note that as in your example, you will need to escape the \
in your java code like this:
Pattern p = Pattern.compile("^[\\w#$]+$");
Upvotes: 8
Reputation: 15029
To add to other answers: I think you are looking for a pattern like "^\\S*$"
, which means: match any number of non-space characters (\\S*
) from beginning (^
) to the end ($
).
Upvotes: 4