Reputation: 3053
Need help in forming regular expression to match text's having pure decimals or alphanumeric decimals but ignoring texts with the only alphanumeric without a decimal or only numeric value or only alphabets.
I tried this ^[a-zA-Z0-9]*[0-9.]*[0-9]$
but it is accepting even alphanumeric values.
Below are the test results which I am expecting.
Text | Result |
---|---|
Test | false |
Test1 | false |
123 | false |
123.12.12 | true |
Test12.123 | true |
Upvotes: 0
Views: 1027
Reputation: 79035
You can use the regex, \p{Alnum}+(?:\.\p{Alnum}+)+
which can be explained as follows:
\p{Alnum}
specifies an alphanumeric character:[\p{Alpha}\p{Digit}]
(?:\.\p{Alnum}+)+
specifies a non-capturing group consisting of a dot followed by one or more alphanumeric characters. The non-capturing group must occur one or more times.Demo:
public class Main {
public static void main(String[] args) {
String[] arr = { "Test", "Test1", "123", "123.12.12", "Test12.123", "123.123Test", "Test123.123Test",
"Test123.12.12Test" };
String regex = "\\p{Alnum}+(?:\\.\\p{Alnum}+)+";
for (String s : arr) {
System.out.println(s + " => " + (!s.matches(regex) ? "false" : "true"));
}
}
}
Output:
Test => false
Test1 => false
123 => false
123.12.12 => true
Test12.123 => true
123.123Test => true
Test123.123Test => true
Test123.12.12Test => true
Upvotes: 1
Reputation: 163277
You might use a lookahead to make sure that there is at least a single digit, and repeat matching 1 or more times the dot.
^(?=[A-Za-z]*[0-9])[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+$
^
Start of string(?=[A-Za-z]*[0-9])
Assert a digit[A-Za-z0-9]+
Match 1+ times any of the listed ranges(?:\.[A-Za-z0-9]+)+
Repeat 1 or more times a dot and again 1 or more of the listed ranges$
End of stringUpvotes: 2