Reputation: 3
I don't know what's wrong with my code, all I want is to accept a mobile number with this kind of format: 09xxxxxxxxx (Always starts in "09" and with a total of 11 digits). All efforts would be appreciated. Thanks in advance.
Here is the picture of the problem
Here are the codes:
String a2= jTextField6.getText();
String a3 = jTextField7.getText();
Pattern p = Pattern.compile("^(09) \\d {9}$");
Matcher m = p.matcher(jTextField5.getText());
if (!m.matches()){
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Invalid Mobile Number", "Error", b);
return;
}
if (null==a2||a2.trim().isEmpty()){
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Fields should not left blank", "Error", b);
return;
}
if(a3==null||a3.trim().isEmpty()){
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Fields should not left blank", "Error", b);
}
else {
int c = JOptionPane.YES_NO_OPTION;
int d = JOptionPane.showConfirmDialog(this, "Confirm Purchase?","Costume 1", c);
if (d==0){
JOptionPane.showMessageDialog( null,"Your costume will be delivered 3-5 working days." +"\n"+"\n"+" Thank You!");
}
Upvotes: 0
Views: 90
Reputation: 51
final String regex = "^09\\d{9}$";
final String string = "09518390956"; //matcb
//final String string = "11518390956"; // fails
//final String string = "09518390956 "; // fails
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}
Upvotes: 0
Reputation: 4959
Use comments mode to ignore whitespace in a regex pattern. This can be done either by passing the Pattern.COMMENTS
flag when compiling the regex pattern, or via the embedded flag expression (?x)
.
Example 1:
Pattern p = Pattern.compile("^(09) \\d {9}$", Pattern.COMMENTS);
Example 2:
Pattern p = Pattern.compile("(?x)^(09) \\d {9}$");
Upvotes: 1
Reputation: 7638
You have to remove the blank spaces in your regex:
Pattern p = Pattern.compile("^(09)\\d{9}$");
otherwise they are gonna be considered as characters that must be present.
Upvotes: 1