username:
^[a-z0-9_-]{3,16}$// any character of a-z, 0-9, underscore and ‘-’password:
similar to username
email:
^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$url:
^(https?:\/\/)?(\da-z\.-]+)\.([a-z\.]{2,6})([/\w\.-]*)*\/?$not
[^]
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
- Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abc|def) Matches abc or def
To help you better understand the regular expressions, Visualized with Regexper
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* By this example you should know how to find a digit string fro the given alphanumeric string
**/
public class RegexMatches{
public static void main(String args[]){
// String to be scanned to find the pattern.
String line ="This order was places for QT3000! OK?";
/**
* . matches any single character except newline
* re* mathches 1 ore more occurrences of preceding expression
* re+ matches 1 ore more of the previous thing
* \d matches digits
*/
String pattern ="(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r =Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if(m.find()){
System.out.println("Found value: "+ m.group(0)); // () means a group
System.out.println("Found value: "+ m.group(1));
System.out.println("Found value: "+ m.group(2));
}else{
System.out.println("NO MATCH");
}
}
}