Java regular expressions are a powerful tool you can use in so many occasions. This post does not intend to make you learn about regular expressions, but to show some real use cases when such patterns can help. We can organize this use cases in following categories:

1. String replacement

a) Remove all letters from a string that contains only digits and letters.

s.replaceAll("[^0-9]", "")

or the equivalent

s.replaceAll("\\D", "")

b) Replace all non-ASCII characters or '?' with space

s.replaceAll("[^\\p{ASCII}]|[\\?]", "")

2. Validation

To validate a string regarding a pattern you have to do the following:

d) Password : Regular expression to validate a password that has at least one digit, at least one lower letter, at least one upper letter and at least one special character from @#$% (and can contain or not any other characters like _,& and so on). Password must be between 6 and 20 characters.

(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20}

3. Extract data by grouping parts of your regular expression

Some examples can be to extract the data between some tags of a html file or to extract some properties values from a json string, like in following example where we want all the names: