Reputation: 77
This is a question on RegEx in Java. I have looked everywhere but could not find anything similar to what I needed. Also, I have spent hours trying on my own.
I am on the last portion of a school lab coded in Java. I am using Eclipse as my compiler. I have built a membership application using Swing components,
One of my fields is for the user to type in the 10-digit phone number. However, I had to make this a JFormatted text field, masking the text box it in this format: "(###) ###-####". So when the program is loaded, that text box looks like this: "(_) -___"
Now, all I need to do is have a regular expression that will make sure the user types in 10 digits. However, I need it to work with the masked format that I used above. This is what I have so far:
pattern = Pattern.compile("\\d{3}\\s\\d{3}-\\d{4}");
matcher = pattern.matcher(phoneText.getText());
if (!matcher.find())
{
phoneText.requestFocus();
JOptionPane.showMessageDialog(null, "Phone entered incorrectly. Phone should be:\n" +
"10 numeric digits.",
"A D D E R R O R",JOptionPane.ERROR_MESSAGE);
return;
}
I believe I have the regEx written to where it accepts the space and the dash in the mask format, but I do not know how to include the parenthesis.
Edit: Adding question in correct format per Andrew Thomas' tip:
What do I need to add to my regEx to include the parenthesis that are already in the formatted text field?
Edit2: Question answered, but adding samples per Bohemians tip so that future students who come across this post can utilize it. Sorry, Im new to this!
Needs to look like:
(123) 456-7890
Upvotes: 5
Views: 6416
Reputation: 1891
Here is a quick solution, when you need to add a brackets in your text-field / phone number field note this is not regex, its jquery based
http://ashfaqahmed.net/jquery-add-prefix-postfix-on-phone-number-field/
Upvotes: 0
Reputation: 95958
You have to match (
and )
(That surround the first 3 digits)
Change it to:
pattern = Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
^^^ ^^^
As you can see, I added \\
before (
and )
. Why?
Some characters have special meaning. And since Regexes are Strings in Java, you need to escape them by \\
(which represents a single \
in Java).
A double backslash escapes special characters to suppress their special meaning, it's like telling:
"Don't take (
as special character, take it as the regular character (
".
Upvotes: 4
Reputation: 697
You can use \\(
and \\)
to use parentheses, try this:
Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
Upvotes: 2