A brief explanation about the basic of regular expression.

What is Regular expression?

It is a technology for expression pattern of text using symbols.

Allow lower and upper case: []

"cat".matches("[cC]at");

Express a range

"cat".matches("[a-fA-Fw-zW-Z]at");

Not in: ^

"cat".matches("[^c]at");

Not in a range

"cat".matches("[^a-z]at");

Match any character: \w

One word character follow by at. Also allow numbers.

"cat".matches("\\wat");

Match any number/digits: \d

One word character follow by at. Also allow numbers.

"cat2".matches("\\wat\\d");

Match space: \s

One word character follow by at. Also allow numbers.

"cat 2".matches("\\wat\\s\\d");

Match group of digits:

Digit and space repeatable at n times {}
"321-333-7652".matches("\\d{3}-\\d{3}-\\d{4}");
Group od different characters []
"321-333.7652".matches("\\d{3}[-,.\\s]\d{3}[-,.\\s]\\d{4}");
One or more what there is before(One or more space in that case): +
"321-333    7652".matches("\\d{3}[-,.\\s]+\d{3}[-,.\\s]+\\d{4}");
Possibility of zero or more: *
"321-3337652".matches("\\d{3}[-,.\\s]*\d{3}[-,.\\s]*\\d{4}");
Zero or just one: ?
"321-3337652".matches("\\d{3}[-,.\\s]?\d{3}[-,.\\s]?\\d{4}");
Min and max range: {n,n}
"321-333-652".matches("\\d{3}[-,.\\s]?\d{3}[-,.\\s]?\\d{3,4}");
Specify one or the other(min 3 digit with no upper limit): {n,}
"321-333-652".matches("\\d{3}[-,.\\s]?\d{3}[-,.\\s]?\\d{3,}");
Reduce repeatable chars:

Before

"321-333-652".matches("\\d{3}[-.,\s]?\\d{3}[-.,\s]?\\d{4}");

After(group repeatable 2 times)

"321-333-652".matches("(\\d{3}[-.,\\s]?){2}\\d{4}");

References:

  • https://www.udemy.com/course/neutrino-java-foundations