Issue
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 &
Solution
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"));
}
}
}
Answered By - Simon G.
Answer Checked By - Timothy Miller (JavaFixing Admin)