user3759895
user3759895

Reputation:

How do I write a regex in java which allow only numbers 0-9 and #

I want the user to input only numbers 0-9 and '#' No spaces, no alphabets and no other special characters.

For ex:

12736#44426 :true
263 35# :false
2376shdbj# :false
 3623t27# :false
#? :false

Here's my code:

boolean valid(String str)
    {
        if(str.matches("[0-9]+|(\\#)"))
        return true;

        else

        return false;

    }

But it returns false for 3256#

I also tried [0-9]+|(#)

I am very noob at regular expressions.

Any help would be appreciated.

Tell me if i am not clear.

Upvotes: 1

Views: 3263

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 30995

You can use a regex like this:

^[\d#]+$

Working demo

enter image description here

The idea is to match digits and symbol # by using using the pattern [\d#] and can be many 1 or many times (using +). And to ensure that the line starts and ends with those characters I use anchors ^ (start of the line) and $ (end of line).

For java remember to escape backslahes as:

^[\\d#]+$

The java code you can use can be:

Pattern pattern = Pattern.compile("^[\\d#]+$");
Matcher matcher = pattern.matcher(YOUR TEXT HERE);

if (matcher.find()) {
    System.out.println("matches!");
}

Or also:

if ("YOUR STRING HERE".matches("^[\\d#]+$")) {
    System.out.println("matches!");
}

If you want to know more about the usage you can check this link:

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#regexjava

Upvotes: 3

vks
vks

Reputation: 67968

^[0-9#]+$

Try this.This will give you your results.

Upvotes: 1

hwnd
hwnd

Reputation: 70732

Add the # character to your character class instead of using the alternation operator.

[0-9#]+

Upvotes: 4

Related Questions