dexter dexter - 1 year ago 111
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 :

311 001
ds311 001NM
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
, but it does not cover all the cases.

Any help is highly appreciated.

Answer Source

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


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()) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download