-3

I want to validate phone number field in swing, so I am writing code to allow user to enter only digits, comma, spaces. For this I am using regular expression, when user enter characters or other than the pattern text field will consume.

My code is not working. Can anyone tell me what the problem is?

String s = c_phone.getText();
    Pattern pattern = Pattern.compile("([0-9\\-\\(\\)\\,]+)");
    Matcher m = pattern.matcher(s);
    if((!m.matches())){
        evt.consume();
    }

Thanks in advance.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Thirunavukkarasu
  • 208
  • 6
  • 26

3 Answers3

1

To only allow digits, comma and spaces, you need to remove (, ) and -. Here is a way to do it with Matcher.find():

Pattern pattern = Pattern.compile("^[0-9, ]+$");
...
if (!m.find()) {
  evt.consume(); 
}

And to allow an empty string, replace + with *:

Pattern pattern = Pattern.compile("^[0-9, ]*$");
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • private void c_phoneKeyReleased(java.awt.event.KeyEvent evt) { // TODO add your handling code here: String s = c_phone.getText(); Pattern pattern = Pattern.compile("^[0-9, ]*$"); //Pattern pattern = Pattern.compile("([0-9\\-\\(\\)\\,]+)"); Matcher m = pattern.matcher(s); if((!m.matches())){ evt.consume(); } } – Thirunavukkarasu Jun 22 '15 at 12:42
0

Your character class includes digits, hyphens, commas and parenthesis.

Note that you do not need to escape the commas and parenthesis, nor the hyphen if placed correctly in the character class.

To validate...

only digits, comma, spaces

"[0-9, ]+" should suffice.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

You can use something like below,

String s = "203 555 0000";
        String s1 = "203,550,0000";
        String s2 = "2035500000";
        Pattern pattern = Pattern.compile("\\d{3}[,\\s]?\\d{3}[,|\\s]?\\d{4}$");
        Matcher m = pattern.matcher(s);
        if(m.matches()){
            //evt.consume();
            System.out.println("Matches");
        }

Explained below:

  • \d matches a digit.
  • {3} is a quantifier that, following \d, matches exactly three digits.
  • | (the vertical bar) indicates alternation, that is, a given choice of alternatives.
  • \s - matches space
  • $ matches the end of a line.

You can enhance it further depend upon your use case.

TheCodingFrog
  • 3,406
  • 3
  • 21
  • 27