How do I validate URNs?

What’s the easiest way to validate that a string is a valid URN?

Edit Using URI is not a correct solution! URIs are allowed to have all kinds of things that URNs can’t, like &


If you only need to validate it, you can use a regular expression. The following will match only RFC2141 compliant URNs:

import java.util.regex.Pattern;

public class UrnTest {
    public final static Pattern URN_PATTERN = Pattern.compile(
        "^urn:[a-z0-9][a-z0-9-]{0,31}:([a-z0-9()+,\-.:[email protected];$_!*']|%[0-9a-f]{2})+$",

    public static void main(String[] args) throws Exception {
        for(String urn : args) {
            boolean isUrn = URN_PATTERN.matcher(urn).matches();
            System.out.println(urn+"  :  "+(isUrn ? "valid" : "not valid"));

Leave a Reply

Your email address will not be published. Required fields are marked *