Since it was necessary to add a validation function for IP addresses and network settings using java, I implemented it using regular expressions. It is the memorandum.
private boolean validateHoge(string target) {
Pattern pattern = Pattern.compile("[Write a regular expression here]");
final Matcher matcher = pattern.matcher(target);
return matcher.matches();
}
You can now use regular expressions in java.
matches ()
checks if the entire string matches, so use find ()
to check if part of the string matches the pattern.
// 0.0.0.0 ~ 255.255.255.Up to 255
Pattern pattern = Pattern.compile("^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])[.]){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
It's straightforward, but I tried to express it like this.
// 1 ~Up to 32
Pattern pattern = Pattern.compile("^([1-9]|[1-2][0-9]|3[0-1](.[0-9]+)?)|32$");
(I realized that it would be easier to change it to Integer after writing and limit it)
// 0~9, a~z, A~z, "."
Pattern pattern = Pattern.compile("[0-9a-zA-z.]+?");
https://regex-testdrive.com/ja/dotest
This site was very convenient.
It is useful when creating regular expressions because it shows the results for each method with matches ()
find ()
.
Recommended Posts