Particular java regular expression - java

How would I check that a String input in Java has the format:
xxxx-xxxx-xxxx-xxxx
where x is a digit 0..9?
Thanks!

To start, this is a great source of regexps: http://www.regular-expressions.info. Visit it, poke and play around. Further the java.util.Pattern API has a concise overview of regex patterns.
Now, back to your question: you want to match four consecutive groups of four digits separated by a hyphen. A single group of 4 digits can in regex be represented as
\d{4}
Four of those separated by a hyphen can be represented as:
\d{4}-\d{4}-\d{4}-\d{4}
To make it shorter you can also represent a single group of four digits and three consecutive groups of four digits prefixed with a hyphen:
\d{4}(-\d{4}){3}
Now, in Java you can use String#matches() to test whether a string matches the given regex.
boolean matches = value.matches("\\d{4}(-\\d{4}){3}");
Note that I escaped the backslashes \ by another backslash \, because the backslashes have a special meaning in String. To represent the actual backslash, you'd have to use \\.

String objects in Java have a matches method which can check against a regular expression:
myString.matches("^\\d{4}(-\\d{4}){3}$")
This particular expression checks for four digits, and then three times (a hyphen and four digits), thus representing your required format.

Related

Java password validation regex

We have password requirements:
Must contain capital letters
Must contain lowercase letters
Must contain numbers
Must contain special characters
There should be no characters repeating one after another
Now our validation regex is:
^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%&*]))
So it doesn't validating the 5th requirement.
How to improve regex to validate characters repeating?
You can remove the outer capture group, and then use a negative lookahead with a backreference to group 1 to exclude 2 repeating characters on after another.
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%&*])(?!.*(.)\1)
In Java
String regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%&*])(?!.*(.)\\1)";
Regex demo
Note that if using the pattern only for a password validation, the minimum length is just 4 characters.
To reduce some backtracking, you could also use negation:
^(?=[^\r\n\d]*\d)(?=[^\r\na-z]*[a-z])(?=[^\r\nA-Z]*[A-Z])(?=[^\r\n!##$%&*]*[!##$%&*])(?!.*(.)\1)
Regex demo

How to allow specific delimiters in between numeric pattern

I have a big Java regex pattern composed of multiple subpatterns concatenated by OR (|). I want to allow multiple delimiters anywhere in between the numbers.
For example, I have the following pattern "(3[47][0-9]{13})|(56022[1-5][0-9]{10}|(5610)[0-9]{12})". How do I allow the following delimiters: equal to (=), backslash (\), dot (.), hyphen (-) and white space ().
These delimiters can appear anywhere (except start and end) and any number of times in between the numbers which match the numeric pattern.
You will have to insert [\s=\\.-]* pattern (it matches zero or more whitespaces, =, \, . and -) in between all digit matching patterns and convert \d{X} into \d(?:[\s=\\.-]*\d){X-1} patterns:
(3[\s=\\.-]*[47][\s=\\.-]*[0-9](?:[\s=\\.-]*[0-9]){12})|(5[\s=\\.-]*6[\s=\\.-]*0[\s=\\.-]*2[\s=\\.-]*2[\s=\\.-]*[1-5][\s=\\.-]*[0-9](?:[\s=\\.-]*[0-9]){9}|(5[\s=\\.-]*6[\s=\\.-]*1[\s=\\.-]*0)[\s=\\.-]*[0-9](?:[\s=\\.-]*[0-9]){11})
See the regex demo
Do not forget to double the backslashes when using the pattern inside a Java string literal:
String part_of_regex = "(3[\\s=\\\\.-]*[47][\\s=\\\\.-]*[0-9](?:[\\s=\\\\.-]*[0-9]){12})|(5[\\s=\\\\.-]*6[\\s=\\\\.-]*0[\\s=\\\\.-]*2[\\s=\\\\.-]*2[\\s=\\\\.-]*[1-5][\\s=\\\\.-]*[0-9](?:[\\s=\\\\.-]*[0-9]){9}|(5[\\s=\\\\.-]*6[\\s=\\\\.-]*1[\\s=\\\\.-]*0)[\\s=\\\\.-]*[0-9](?:[\\s=\\\\.-]*[0-9]){11})";

Regex for a random set of chars and digits

I am looking for a regex that matches only when it sees a string that is randomly filled by digits and chars.
For example, adfak332arg3 is allowed but 332352 and fagaaah are not allowed. .*[^\\s] looks fine for strings with only chars but how to fix it to accepts the desired strings and refuses the other two types?
Use a positive lookahead (?=) to ensure that the string contains required characters.
^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$
Test this regex pattern here.
You can try this regex
"[\\d\\w]*\\d\\w[\\d\\w]*|[\\d\\w]*\\w\\d[\\d\\w]*"
If you need just a mixed string of characters A-Z, a-z and 0-9 you can use:
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])$
If you want to force the string to have a minimum number of characters in your string you can use (e.g. minimum 8 in the string):
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$
If you want to have a string length from min-length to max-length then use (e.g. string of at least 5 characters and max 20 characters):
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{5,20}$
To ensure that an input contains digits as well as characters, you could use this regex:
^(?:[A-Za-z]+\\d+|\\d+[A-Za-z]+)[A-Za-z\\d]*$
The regex ensures that the input contains at least a number and a character, and allows only numbers or characters (no special characters etc.)
(?:[A-Za-z]+\d+|\d+[A-Za-z]+) ensures that it starts with one or more characters followed by digits or alternatively |\d+[A-Za-z]+ one or more digits followed by one or more characters
[A-Za-z\d]* allows any number of characters or digits after the previous check
^ and $ to match starting and ending anchor
Regex101 Demo
Hope this helps!
Try this Regex.
[A-z][0-9]|[0-9][A-z]

Regex + sign followed by numbers

Hi i want to find Strings like "+19" in Java
so a + sign followed by infinite amount of numbers.
How do i do this?
Tried "+[0123456789]"
and "\+[0123456789]"
thank you :)
This is the regex you want to use:
\\+\\d+
Two kinds of plus are being used here. The first is escaped with two backslashes because it is treated as a literal. The second one means match 1 of more times (i.e. match any digit one or more times).
Code:
String input = "+19";
if (input.matches("\\+\\d+")) {
System.out.println("input string matches");
}
Yes, to match a plus you need to escape it with two backslashes in a C string literal that Java uses. A literal plus needs to be either escaped or put into a character class, [+]. If you just use a plus symbol, it becomes a quantifier that matches the previous symbol or group one or more number of times.
Also, note that the \d shorthand digit class can match more than just ASCII digits if Pattern.UNICODE_CHARACTER_CLASS flag is passed to Pattern.compile (or embedded (?U) flag is added at the start of the pattern). It is advised to use unambiguous patterns in case the code might be maintained or enhanced/adjusted by different developers later.
Most people prefer patterns without escaping backslashes if possible since that allows to avoid issues like the one you faced.
Here is a version of the regex that does not require any escaping:
"[+][0-9]+"
Also, the plus quantifier does not match an infinite number of digits, only MAX_UINT number of times.

Java regular expression to validate numeric comma separated number and hyphen

Valid1: 2
valid2: 3-5
Valid3: 2,4-6
valid4: 2,4,5
valid5: 2-7,8-9
Valid4: 2,5-7,9-13,15,17-20
All the expression on the above should be valid in one regex.
the digit in the left side of hyphen should be smaller than right hand side.
First, as #MikeFHay suggested above, regex were not made to check if one digit is bigger than the other (for that you'll have to parse the expression). If we'll ignore that requirement - the rest can be achieved via the following regex:
((\d\,(?=\d))|(\d\-(?=\d))|\d)+
in Java:
"((\\d\\,(?=\\d))|(\\d\\-(?=\\d))|\\d)+"
Explanation:
This regex uses lookahead to validate that each comma or dash is preceded and followed by a digit: (\d\,(?=\d)) so that each "substring" that contains a dash/comma will have to be in the format of: digit,digit or digit-digit.
Of course that a number that doesn't contain commas/dashes is also valid - hence the rightmost side of the or which is simply a \d
Link to online demo

Categories

Resources