1

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_$#]

2 Answers 2

8

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#$]+$");
Sign up to request clarification or add additional context in comments.

8 Comments

So how to make it not allow single or multiple spaces in between . Do I need to do it separately ?
No, this should just work as is. single or multiple spaces will not be allowed by this. The suggestion by @rodion to use \S is also a good one, but would produce similar results. I might favour it as it is more specific about what is (not) being matched.
Can you please provide some additional check to the above check in the Original post ? The expression you suggested does not seem to working for few cases .
@SandeepPathak i'm happy to add additional info, what cases are not matching? If i know that i might better understand what you need.
@SandeepPathak would be useful if you showed us what those cases are
|
4

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 ($).

1 Comment

Can you please provide some additional check to the above check in the Original post ? The expression you suggested does not seem to working for few cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.