I want to validate a String in java that contains the following order:
SAVA950720HMCLZL04
That is, four letters, six numbers, six letters and finally two numbers.
I was reading about Regular Expressions but I can't understand how to implement it.
I did this method to validate the first four letters.
public void name(String s){
Pattern pat=Pattern.compile("[a-zA-z]{4}");
Matcher mat=pat.matcher(curp);
if(mat.matches()){
JOptionPane.showMessageDialog(null, "Validating");
}else{
JOptionPane.showMessageDialog(null, "Check your data. please", "error",JOptionPane.ERROR);
}
}
I think that I might be wrong because I don't know how to implement it correctly, any help about what might be the correct solution to my problem?.
[A-z]matches more than just letters. Thematches()method anchors the regex, so you can only match strings of 4 chars. So, you needmatches("[A-Za-z]{4}[0-9]{6}[A-Za-z]{6}[0-9]{2}")A-zshould beA-Z. To represent digits use[0-9]or\d(in String literals you need to additionally escape\so it will look like"\\d"). Alsomatches()checks if regex can match entire string, not just part of it.