Created
June 6, 2018 00:02
-
-
Save g4rcez/36c43810a0c84a8f1150836c93edbe32 to your computer and use it in GitHub Desktop.
Validação de URI via regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
public abstract class FilterURI { | |
private static final String numbers = "^[0-9]+$"; | |
private static final String uuid = "^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$"; | |
private static final String alphaNumber = "^[a-zA-Z0-9]+$"; | |
private static final String cpf = "^((\\d{3})(|\\.)){2}(\\d{3})(|-)\\d{2}$"; | |
private static final String cnpj = "^\\d{2}((|\\.)\\d{3}){2}(|\\/)\\d{4}(|-)\\d{2}$"; | |
private static String regex2String(String regex) { | |
String escape = "\\\\\\"; | |
return regex.replaceAll("\\[", escape + "[") | |
.replaceAll("]", escape + "]") | |
.replaceAll("}", escape + "}") | |
.replaceAll("\\{", escape + "{") | |
.replaceAll("\\(", escape + ")") | |
.replaceAll("\\)", escape + ")") | |
.replaceAll("\\+", escape + "+") | |
.replaceAll("\\$", escape + "$") | |
.replaceAll("\\^", escape + "^"); | |
} | |
private static String transform(String regexUri) { | |
HashMap<String, String> regexMap = new HashMap<>(); | |
String string = regexUri; | |
regexMap.put("{numbers}", regex2String(numbers)); | |
regexMap.put("{alphaNum}", regex2String(alphaNumber)); | |
regexMap.put("{cpf}", regex2String(cpf)); | |
regexMap.put("{uuid}", regex2String(uuid)); | |
regexMap.put("{cnpj}", regex2String(cnpj)); | |
for (String key : regexUri.split("/")) { | |
String element = regexMap.get(key); | |
if (element != null) { | |
string = string.replaceAll(regex2String(key), element); | |
} | |
} | |
return string; | |
} | |
private static Boolean compare(String uri, String uriRegex) { | |
if (!uri.startsWith("/")) return false; | |
String[] uriSplit = uri.split("/"); | |
String[] regexSplit = transform(uriRegex).split("/"); | |
for (int index = 0; index < uriSplit.length; index++) { | |
if (!uriSplit[index].matches(regexSplit[index])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
String uri = "/cliente/25/32"; | |
String regexTransform = "/cliente/{numbers}/{numbers}"; | |
System.out.println(compare(uri, regexTransform)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment