Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate URNs?

Tags:

java

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 &

like image 415
ykaganovich Avatar asked Mar 30 '11 21:03

ykaganovich


3 Answers

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 static final Pattern URN_PATTERN = Pattern.compile(
        "^urn:[a-z0-9][a-z0-9-]{0,31}:([a-z0-9()+,\\-.:=@;$_!*']|%[0-9a-f]{2})++$",
        Pattern.CASE_INSENSITIVE);


    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"));
        }
    }
}
like image 109
Simon G. Avatar answered Nov 16 '22 21:11

Simon G.


I recently released urnlib. It implements a class for representing an Uniform Resource Name (URN). It also implements parsing and serialization according to the constraints defined in RFC 2141.

It's released on Maven Central and aims to serve as a network identifier handling library just like the native Java URL and URI classes.

like image 3
Ralf Claussnitzer Avatar answered Nov 16 '22 21:11

Ralf Claussnitzer


You can try jcabi-urn and its class com.jcabi.urn.URN

like image 2
yegor256 Avatar answered Nov 16 '22 21:11

yegor256