dexter dexter - 28 days ago 24
Java Question

Regex in java for unstructured pincode

I have a sample of texts on which i am trying to apply the regex , but unable to cover all the cases

Sample of texts :

311001
311 001
ds311001NM
ds311 001NM
asd,.;546798;l';
asd,.;546798;l';
asd,.; 546798;l';
asd,.; 546798 ;l';
asd,.; 546 798 ;l';
asd,.;546 798 ;l';


pin codes can have spaces in between or may not have . I tried with regex
[1-9]{3}\\s*[0-9]{3}
, but it does not cover all the cases.

Any help is highly appreciated.

Answer

The regex you have matches 3 digits from the 1-9 range so, it cannot find 200 345 type of PIN.

You need a simpler regex

\d{3}\s*\d{3}

See the regex demo

Java demo:

List<String> strs = Arrays.asList("311001","311 001","ds311001NM","ds311 001NM","asd,.;546798;l';","asd,.;546798;l';","asd,.; 546798;l';","asd,.; 546798 ;l';","asd,.; 546 798 ;l';","asd,.;546 798 ;l';");
Pattern p = Pattern.compile("\\d{3}\\s*\\d{3}");
for (String str : strs) {
    Matcher m = p.matcher(str);
    if (m.find()) {
        System.out.println(m.group());
    }
}
Comments