简体   繁体   中英

Specific string format in java

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?.

Regex pattern in your case would be:

[a-zA-Z]{4}[0-9]{6}[a-zA-Z]{6}[0-9]{2}

Find matching is simple:

public void name(String s){
    String pattern = "[a-zA-Z]{4}[0-9]{6}[a-zA-Z]{6}[0-9]{2}";
    boolean match = s.matches(pattern);
    if (match) {
        ...
    } else {
        ...
    }
}

You can test regex from here https://regex101.com/

Edit

I used [0-9] instead of \\d to ensure the safety matching for only digits. More details can be found here: Should I use \\d or [0-9] to match digits in a Perl regex?

  1. Matcher.match attempts to match entire String against the pattern and your current pattern validates only 4 characters. Here is what you can do to test you regular expression:

    • You can put .* at the end of regular expression to match rest of the String
    • You can alternatively use Matcher.find or Matcher.lookingAt to match against substring
  2. Your pattern has a typo, second interval is too wide Az vs AZ

Try this Regex pattern:

[a-zA-Z]{4}\d{6}[a-zA-Z]{6}\d{2} 

The above will validate for four letters, six numbers, six letters and finally two numbers.

package com.stackoverflow._42635543;

import java.util.regex.Pattern;

public class Main {

  public static void main(String[] args) {
    Pattern pat = Pattern.compile("[A-Za-z]{4}[0-9]{6}[A-Za-z]{6}[0-9]{2}");

    if (pat.matcher("SAVA950720HMCLZL04").matches()) {
        System.out.println("match");
    } else {
        System.out.println("no match");
    }

    if (pat.matcher("SAVA950720HMCLZL045").matches()) {
        System.out.println("match");
    } else {
        System.out.println("no match");
    }
  }
}

produces

match
no match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM