Suppose you want to validate a String to check that a person's gender has been entered correctly.
You could use the following program to check if the test data was valid
```java
String test = "M";
if(test.equals("M")|test.equals("F")){
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
```
Another way would be to use the matches(regex) method.
The matches() method returns true if the regex matches String text.
Here's the same program written that way:
```java
String test = "M";
if(test.matches("M|F")) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
```
You can give a choice of letters using \[ \], so
```java
test.matches("gr[ea]y");
```
matches grey and gray.
so you could use
```java
test.matches("[MmFf]")
```
to match upper and lower case letters.
You might want to accept M or Male
Use
```java
test.matches("M(ale)?");
```
The question mark means the (ale) part is optional.
Suppose you want to check the user has entered lowercase letter, a-z. Use
```java
test.matches("[a-z]");
```
To check for exactly three lowercase letters:
```java
test.matches("[a-z]{3}");
```
To check for any number of lowercase letters:
```java
test.matches("[a-z]+");
```
To check for any letters, upper or lowercase:
```java
test.matches("[a-zA-Z]");
```
You can do the same thing with digits
```java
test.matches("[0-9]");
```
checks if the user has entered a digit.
```java
[0-9]+
```
checks for any number of digits.
Use
```java
[1-9][0-9]{3}
```
to match a number between 1000 and 9999.
```java
[1-9][0-9]{2,4}
```
matches a number between 100 and 99999
### 1.1 White Space
You can check for spaces by using
```java
"\\s" (Double backslash s)
```
### 1.2 Post Codes
Most post codes have the following regex for the first part
```java
[A-Z][A-Z][0-9]
```
### 1.3 Misc
The following mimics hangman, filling in correctly guessed letters.
`String guesses` is the letters guessed so far
`String answer` is the text to be guessed.
```Java
guesses = guesses + txtInput.getText().toLowerCase();
//guesses keeps a record of the letters entered so far
lblAnswer.setText(answer.replaceAll("[^"+guesses+"]","*")+ " " + guesses);
//use a regex to replace the letters NOT in the guesses string with *s
```
## Exercise
Write regular expressions to validate the following:
1. Car number plates of the type MA05 FGH
2. Car number plates of the type P123 ASD
3. Post codes of the type E6 1FG
4. Post codes of the type OL1 1AA and OL12 3PL
5. Post codes of the type M13 1PP and all the above
6. An email address of the type [
[email protected]](mailto:
[email protected])
7. Modify the above email address so it will also accept .co.uk, .org and and .sch.uk addresses
8. A simple password generator uses A=4, E =3, L= 7, O= 0 and S =5 to change words such as PASSWORD to P455W0RD. Write a program using replaceAll to do the same.