Damo
Damo

Reputation: 11550

Regex for optional leading forward slashes

I need to validate shipping container numbers. There is an industry standard that says only alpha-numeric and 11 characters in length is acceptable. eg: FBXU8891735

However there is also a standard industry practice where the first 4 characters can be forward-slashes eg: ////8891735

I have 2 requirements - firstly to validate the container numbers (eg. matches()) and secondly to clean the container numbers (eg. replaceAll())

System.out.println("MSCU3720090".matches("[a-zA-Z0-9]{11}"));    //true - ok
System.out.println("////3720090".matches("[a-zA-Z0-9]{11}"));    //false - fail

System.out.println("MSCU3720090".replaceAll("[^a-zA-Z0-9]*", ""));   //MSCU3720090 - ok
System.out.println("////3720090".replaceAll("[^a-zA-Z0-9]*", ""));   //3720090 - fail

I know that for matches() I can use an alternate eg:

[a-zA-Z0-9]{11}|////[a-zA-Z0-9]{7}

However this seems ugly and I'm not sure how to use it for replaceAll().

Can someone suggest a better regex to satisfy both requirements (or one for each requirement)?

Thanks.

Upvotes: 1

Views: 1676

Answers (2)

Sameer Shemna
Sameer Shemna

Reputation: 906

In case someone wants a proper validation of Cargo Container Number ISO 6346, please refer my Javascript class for the purpose or Patrik Storm's PHP Class.

Upvotes: 0

Anon.
Anon.

Reputation: 60033

"((?:[a-zA-Z0-9]{4}|/{4})[a-zA-Z0-9]{7})"

Then just examine the contents of capture group 1 for the number.

Upvotes: 1

Related Questions