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 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"));
}
}
}
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.
You can try jcabi-urn and its class com.jcabi.urn.URN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With